Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vue.js 计算属性响应本地存储更改_Vue.js_Local Storage_Vuex - Fatal编程技术网

Vue.js 计算属性响应本地存储更改

Vue.js 计算属性响应本地存储更改,vue.js,local-storage,vuex,Vue.js,Local Storage,Vuex,我正在将阵列保存到本地存储中 以及从阵列中添加/删除,如 我希望在localstorage中将新项目添加到阵列时,组件中的阵列计数会更新 我正在使用计算属性: numOfCodes: { // getter get: function() { let storageItems = localStorage.getItem("items"); if (storageItems) { var items = JSON.pa

我正在将阵列保存到本地存储中

以及从阵列中添加/删除,如

我希望在localstorage中将新项目添加到阵列时,组件中的阵列计数会更新

我正在使用计算属性:

 numOfCodes: {
      // getter
      get: function() {
        let storageItems = localStorage.getItem("items");
        if (storageItems) {
          var items = JSON.parse(storageItems);
          return items.length;
        }
        return 0;
      }
    }
计数未按预期更改。它保持不变


我尝试过使用vuex,但仍然存在问题。目标是让该值对本地存储更改作出反应

本地存储不共享Vue的反应系统。整个过程由Vue自己处理。另见。我认为您应该能够通过强制Vue使用更新其所有组件来手动触发重新渲染。但是,请记住,无论何时更新localStorage或希望更新localStorage,都必须触发重新渲染。

我认为解决方法是使用vuex,我模拟了以下示例:

在您的组件上:

computed: {
    ...mapGetters({
        itemsCount: 'mockLocalStorage/itemsCount'
    })
},

created() {
    this.setItems(...);
},

methods: {
   ...mapActions({
       setItems: 'mockLocalStorage/setItems'
   })
}
在vuex中:

state = {
    items: []
};

getters = {
    itemsCount: state => state.items.length
};

actions: {
    setItems({ commit }, items) {
        localStorage.setItem('items', items);
        commit('setItems', items);
    }
};
this.itemsont
将在您的组件中起反应作用,您可以创建更多操作来添加和删除单个项。

使用

props: ['storageItems', 'itemsLength'],
watch: {
    storageItems: function(newVal, oldVal) {
        this.storageItems = newVal
        this.itemsLength = newVal.length
    }
}