How to listen for state changes in vuex in vuejs and handle them uniformly?

A todoList small demo, data is made based on vue.js and vuex to be stored in vuex.

clipboard.png

listlocalstoragevuejswatch


mutation:


:

clipboard.png

this feels so bulky and troublesome, and the essential requirement is to "monitor" changes in list and do a unified treatment. How to do it?

made an online demo, god to help take a look at the demand:
https://codepen.io/quiettroja.

Sep.01,2021

//
  computed: {
    changeMemberTab() {
      return this.$store.state.changeMemberTab;
    }
  },
  //
  watch: {
    changeMemberTab(val) {
      document
        .getElementById("memberTabHeader")
        .getElementsByTagName("li")[this.$store.state.changeMemberTab].click();
    }
  },

have a suggestion:

in fact, you encapsulate the utils.js yourself and then encapsulate the setLocalStorage, but it is still used directly in the mutations, and it is not in the component when you set it up, it is still in the unified store

.

and mutations names are suggested to be capitalized


you can see that the getter, of vuex is equivalent to the calculation property of store. But I don't think you can save much of your repetitive code in this line of code


computed: {
    watchTodo() {
      return this.$store.getters.todo.length;
    }
  },
  watch: {
    watchTodo: {
      handler(newVal, oldVal) {
        console.log("changed");
        storage.set("todo", this.$store.state.todoThings);
      },
      deep: true
    }
  },

can listen for operations, and storage is encapsulated


can be monitored, as long as

import {mapState} from 'vuex'

computed: {
    ...mapState(['list'])
},
watch: {
    list: {
        handler: newVal=>{
            localStorage.setItem('todo-list',JSON.stringify(newVal))
        },
        deep: true
    }
}
is used in the calculation attribute.
Menu