首页 > 解决方案 > 为什么输入中的值没有加载来自 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);
       },
    }
});

标签: javascriptvue.jsvuex

解决方案


您正在尝试设置没有任何设置器的计算属性的值。现在,没有为您的计算属性声明任何 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);
  }
 }
};

推荐阅读