javascript - 为什么本地存储正在更改任务列表中的每个条目
问题描述
本地存储应该只保存已按下完成按钮的任务的状态。目前,当我刷新页面时,所有任务都标记为已完成。
<template>
<button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
{{ buttonText }}
</button>
</div>
</template>
<script>
export default {
props: 'itemId', required: true,
data() {
return {
index: 'this.itemId',
status: ''
}
},
methods: {
on_order_button_click() {
this.status = !this.status;
localStorage.setItem('index', this.status);
}
},
mounted() {
this.status = localStorage.getItem('index') === "true";
},
computed: {
buttonText() {
return this.status === true ? "Completed" : "Complete";
},
order_button_style() {
return this.status === true
? "btn btn-danger"
: "btn btn-primary";
}
}
};
</script>
解决方案
在设置 localstorage 的调用中,您使用字符串“索引”键设置项目,而不是组件的索引数据属性。有了你现在所拥有的,所有组件都从同一个本地存储键读取。
例如,更改:
mounted() {
this.status = localStorage.getItem('index') === "true";
},
至:
mounted() {
this.status = localStorage.getItem(this.index) === "true";
},
另外,我认为您将数据属性设置为等于传递的属性的方式不起作用。我以前从未见过。我认为您只是将索引数据属性设置为等于字符串文字'this.itemId'
。
我已经重写了您的组件,试图清除我认为存在的错误。让我知道这个是否奏效。
<template>
<button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
{{ buttonText }}
</button>
</template>
<script>
export default {
props: {
itemId: {
type: String,
required: true,
}
},
data() {
return {
status: false,
}
},
methods: {
on_order_button_click() {
this.status = !this.status;
localStorage.setItem(this.itemId, this.status);
}
},
mounted() {
this.status = localStorage.getItem(this.itemId) === "true";
},
computed: {
buttonText() {
return this.status === true ? "Completed" : "Complete";
},
order_button_style() {
return this.status === true ?
"btn btn-danger" :
"btn btn-primary";
}
}
};
</script>
推荐阅读
- delphi - 无法调用 MessageDlg
- node.js - 从 Visual Studio 将节点应用程序部署到谷歌云
- amazon-web-services - AWS ALB DNS 的安全性
- javascript - 使用 Kotlin 和 External 创建 React 应用程序
- numpy - 如何将 numpy 数组邻接列表转换为 numpy 数组邻接矩阵?
- javascript - Gatsby 静态/动态混合组件
- javascript - Html 不显示 Typescript 的结果
- python - SQLAlchemy:如何引用过滤字段
- swift - Swift 中的类型 '()' 指的是什么
- ruby-on-rails - 更正我的代码:Sort_by 2 属性,如果它是两个值之一,则第一个属性遵循第二个属性