store.watch函数返回unwatch函数,如文档所述。
我需要一次监视自己的状态。因此,我可以在watch方法的第二个参数回调函数中调用unwatch函数,还是应该在其他地方调用它?
var unwatch = this.$store.watch(
state => state.foo,
() => {
someMethod();
unwatch(); // Is this work ?
}
)
PS:将监视器记录到控制台后,我无法理解其状态。
答案 0 :(得分:2)
那么,我可以在watch方法的第二个参数回调函数中调用unwatch函数,还是应该在其他地方调用它?
答案:
在手表回调中调用它即可!
在示例中,我有一个count
存储在vuex存储中,还有一个localCount
存储在组件的状态中。
只要商店中的count
发生变化,我都会调用一种方法来更新localCount
。 localCount
成功更新一次:
模板:
<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();
}
)