javascript - 为什么输入中的值没有加载来自 vuex 的值?
问题描述
我需要将input中输入的值保存到vuex中,然后在vuex store 中保存在localstorage中,然后如果应用程序关闭,重新打开时,应该将保存在 localstorage 中的值返回到 input。现在由于某种原因我的输入值没有保存。请告诉我我做错了什么,或者如果可能,请更正代码。谢谢!
组件
<f7-list-input
placeholder="Username"
type="text"
v-bind:value="name"
@input="onPersist"
/>
export default {
mounted() {
if (localStorage.name) {
this.name = localStorage.getItem('name');
}
},
computed:{
name(){
return this.$store.state.name;
}
},
methods:{
onPersist(){
this.$store.commit('persist',event.target.value);
}
}
};
</script>
VUEX商店
export default new Vuex.Store({
state: {
name: ''
},
mutations: {
persist(state,payload){
state.name = payload;
localStorage.setItem('name', state.name);
},
}
});
解决方案
您正在尝试设置没有任何设置器的计算属性的值。现在,没有为您的计算属性声明任何 set 方法,这行代码
this.name = localStorage.getItem('name');
不会导致任何反应性更改或改变 vuex 存储中的状态。您应该阅读有关vuex 中表单处理的更多信息,以更好地理解它。
要解决您的问题,您只需使用从本地存储中获取的数据在已安装的挂钩中提交“持久”突变。
<f7-list-input
placeholder="Username"
type="text"
:value="name"
@input="onPersist"/>
export default {
mounted() {
if (localStorage.name) {
// 'name' is a computed property without a setter
// hence, below line in your code doesn't reflect change
//
// this.name = localStorage.getItem('name');
//
// instead you should commit the value to the store
// and let vuex take care of everything
const existingName = localStorage.getItem('name');
this.$store.commit('persist', existingName);
}
},
computed:{
name(){
return this.$store.state.name;
}
},
methods:{
onPersist(){
this.$store.commit('persist',event.target.value);
}
}
};
推荐阅读
- javascript - 获取纯 JavaScript 的 polyfill
- react-native - React-Native 0.57.5 React Navigation 3 不工作
- python - Python:在查找列表中最小数字的最长序列的长度时输出不正确
- sitecore - 在 sitecore 中以编程方式在内容编辑器中切换语言
- javascript - 快速路由练习返回奇怪的错误
- c# - 有没有一种方法可以更有效或更快地在 excel 文件中写入大型数据表?
- python - 使用 Celery 中的内存中断时,同步处理所有待处理的任务
- angular - 错误时来自服务器的请求响应
- wordpress - DirectAdmin 托管 - 默认页面重定向
- c - 编译 OpenGL 时出现 GLUT 库问题