[Vuejs]-Computed property react to localstorage change

0👍

The localStorage does not share the reactivity system of Vue. This whole process is handled by Vue itself. See also here. I think you should be able to manually trigger a re-render by forcing Vue to update all of its components using forceUpdate. However, keep in mind that you would have to trigger the re-render whenever you update the localStorage or whenever you expect it to be updated.

0👍

I think a solution to this would be to use vuex, I’ve mocked up an example below:

On your component:

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

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

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

In vuex:

state = {
    items: []
};

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

actions: {
    setItems({ commit }, items) {
        localStorage.setItem('items', items);
        commit('setItems', items);
    }
};

this.itemsCount would then be reactive in your component, and you could create a few more actions to add and remove individual items.

-1👍

Use a watcher.

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

Leave a comment