【问题标题】:Why is the value in input not load with a value from vuex?为什么输入中的值没有加载来自 vuex 的值?
【发布时间】:2019-09-02 10:44:29
【问题描述】:

我需要将 input 中输入的 value 保存到 vuex 中,然后在 vuex 存储中保存localstorage,然后如果应用程序关闭,重新打开时,应该将保存在localstorage中的值返回输入。现在由于某种原因我的输入值没有保存。请告诉我我做错了什么,或者如果可能,请更正代码。谢谢!

组件

<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);
       },
    }
});

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    您正在尝试设置没有任何设置器的计算属性的值。现在,没有为您的计算属性声明任何 set 方法,这行代码

    this.name = localStorage.getItem('name');
    

    不会导致任何反应性更改或改变 vuex 存储中的状态。您应该阅读更多关于form handling in vuex 的信息以更好地理解它。

    要解决您的问题,您只需使用从本地存储中获取的数据,在您的挂载钩子中提交 'persist' 突变。

    <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);
      }
     }
    };
    

    【讨论】:

    猜你喜欢
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 2013-12-04
    • 2021-11-27
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多