Vuex商店监视

时间:2019-07-30 09:01:52

标签: vuex

store.watch函数返回unwatch函数,如文档所述。

我需要一次监视自己的状态。因此,我可以在watch方法的第二个参数回调函数中调用unwatch函数,还是应该在其他地方调用它?

var unwatch = this.$store.watch(
  state => state.foo,
  () => {
    someMethod();
    unwatch();  // Is this work ?
  }
)

PS:将监视器记录到控制台后,我无法理解其状态。

1 个答案:

答案 0 :(得分:2)

  

那么,我可以在watch方法的第二个参数回调函数中调用unwatch函数,还是应该在其他地方调用它?

答案:

  

在手表回调中调用它即可!

这里是codesandbox example

在示例中,我有一个count存储在vuex存储中,还有一个localCount存储在组件的状态中。

只要商店中的count发生变化,我都会调用一种方法来更新localCountlocalCount成功更新一次:

模板:

  <div id="app">
    Local Count {{ localCount }}
    <hr>
    store count {{ $store.state.count }}
    <hr>
    <button @click="increase">Increase</button>
  </div>

脚本:

  data: () => ({
    localCount: 0
  }),

  created() {
    const unwatch = this.$store.watch(
      state => state.count,
      () => {
        this.myMethod();
        unwatch();
      }
    );
  },

  methods: {
    myMethod() {
      this.localCount++;
    },
    increase() {
      this.$store.commit("increase");
    }
  }
  

何时何地调用unwatch函数取决于您的需要。您甚至可以将取消监视功能存储到vue实例,当您不想再观看时,可以执行this.unwatch()

this.unwatch = this.$store.watch(
  state => state.foo,
  () => {
    someMethod();
  }
)