我正在开发一个小项目来学习 Vue js。它应该是一个习惯追踪器。我目前有一个错误,如果您重新加载页面并添加新的习惯,我应该更改背景的功能将无法正常工作。
这里显示了错误 这是我的数组的样子:
0
:
{id: 0, title: "1", ready: false}
1
:
{id: 1, title: "123", ready: false}
2
:
{id: 2, title: "123", ready: false}
3
:
{id: 0, title: "123", ready: true}
我明白为什么它不起作用,因为我使用计数器来分配 id,重新加载时重置为 0。
<div class="q-pa-md" v-for="(habit, index) in habits" :key="habit.id">
<q-card class="my-card" :id="habit.id" ref="card">
<q-card-section>
<q-checkbox
id="checkbox"
v-model="habit.ready"
@click="changeToTransparent(habit)"
>
</q-checkbox>
{{ habit.title }}
<q-btn-dropdown flat class="more" icon="more_horiz">
<q-list>
<q-item clickable v-close-popup @click="deletehabit(index)">
<q-item-section>
<q-item-label>Delete</q-item-label>
</q-item-section>
</q-item>
<q-item clickable v-close-popup @click="edithabitbutton(index)">
<q-item-section>
<q-item-label>Edit</q-item-label>
</q-item-section>
</q-item>
</q-list>
</q-btn-dropdown>
</q-card-section>
</q-card>
<div>
let counter = 0;
const habits = ref([]);
const addHabit = () => {
habits.value.push({ id: counter++, title: habittitle.value, ready: false });
savetolocalstorage();
habittitle.value = "";
};
const changeToTransparent = (habit) => {
if(document.getElementById(habit.id) != null) {
if (habit.ready) {
document.getElementById(habit.id).style.backgroundColor =
"rgba(170,193,200,0.25)";
savetolocalstorage();
} else {
document.getElementById(habit.id).style.backgroundColor = "";
savetolocalstorage();
}
}
}
关于如何解决这个问题有什么想法吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您需要加载本地存储并将长度设置为计数器值。我在这里做了一个工作示例。我还改进了你的代码,使其更符合 Vue 的概念。正如 @Rahul Purohit 指出的,保存时需要
JSON.stringify结果,加载时需要JSON.parse。