Detect & Watch the change of State
文章目录

VueJs: Detect/Watch the change of State

DO NOT USE Vue.Watch(), use Vuex.Watch() instead

Solution, but not a best practise

1
2
3
4
5
watch: {
  '$store.state.drawer'function({
    console.log(this.$store.state.drawer)
  }
}

Best Practise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
created() {
    this.$store.watch(
      state => state.message.show,
      val => {
        const msg = { ...this.$store.state.message };
        if (val === true) {
          this.$message({
            message: msg.message,
            type: msg.type
          });
          this.$store.commit("message", {
            type: undefined,
            message: undefined,
            show: false
          });
        }
      }
    );
  },

watch

  • watch(fn: Function, callback: Function, options?: Object): Function

Reactively watch fn‘s return value, and call the callback when the value changes. fn receives the store’s state as the first argument, and getters as the second argument. Accepts an optional options object that takes the same options as Vue’s vm.$watch method.

To stop watching, call the returned unwatch function.

Arguments:

  1. fn: Function: we may check the return value of this function
  2. If the returned value from first arg changed, trigger the second argument: the callback: Function
  3. options?: Object is optional options object
  4. Call the final returned function then you can stop watch the function