[英]trigger method directly from computed (Vue.js)
我正在使用Vue 3
和VueX
。
我想知道如果我的returned value
true
,是否可以签入computed
,而不是直接触发我的method
而无需观察者。
信息: this.$store.state.boolean
有时会发生变化,所以如果是true
我想触发我的方法。
下面你可以看到一个我现在如何做的例子:
//computed
computed: {
test() {
return this.$store.state.boolean;
},
}
//watch
watch: {
test(boolean) {
if (boolean == true) {
this.trigger_method();
}
}
},
//methods
method: {
trigger_method() {
console.log("TEST");
}
}
你真的不应该在你的计算函数中有副作用。 见这里: https://vuejs.org/guide/essentials/computed.html#getters-should-be-side-effect-free
无论如何要回答您的问题,您可以执行以下操作:
//computed
computed: {
test() {
if (this.$store.state.boolean) {
this.trigger_method();
}
// as this is a getter function you will need to return something.
return this.$store.state.boolean
},
}
我为您的问题推荐的方法是:
watch: {
'$store.state.boolean': function() {
if ($store.state.boolean === true) {
this.trigger_method();
}
}
}
有了这个,你不需要计算。 如果您在代码模板或任何方法中的某处需要计算值,您应该保留它并使用您已经在使用但试图避免的计算和观察方法。
第三个选项,如果 Function 不是特定于组件的,您可以为您的 Vuex 商店定义订阅者,请参见此处: https://vuex.vuejs.org/api/#subscribe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.