Vuex 变异订阅触发多次
Vuex mutation subscription trigger multiple times
我正在使用 vue CLI 并创建了多个组件
app.vue
import home_tpl from './home.vue';
new vue({
el : '#app',
components : { home_tpl },
created(){
this.$store.subscribe((mutation) => {
switch(mutation.type){
case 'listing':
alert();
break;
});
}
})
然后我还有一个听众 home.vue
home.vue
export default{
created(){
this.$store.subscribe((mutation) => {
switch(mutation.type){
case 'listing':
alert();
break;
});
}
}
问题是当我 this.$store.commit('listing',1);
这个 this.$store.subscribe((mutation) => {
触发两次时,这是预期的行为,因为我从不同的文件中两次收听事件,有没有办法让它只触发一次每个组件?
我将突变侦听器调用到 home.vue
的原因是因为有一个事件我只想 运行 专门针对该组件。
您的示例代码监听 listing
app.vue
和 home.vue
的变化,但根据您的帖子,他们似乎对不同类型的变化感兴趣?
如评论所述,如果您只对一些更改而不是 所有 商店的更改感兴趣,watch
应该是更好的方法。类似于:
// home.vue
new vue({
el : '#app',
components : { home_tpl },
created(){
this.$store.watch((state, getters) => state.stateHomeIsInterested, (newVal, oldVal) => {
alert()
})
}
})
// app.vue
export default{
created(){
this.$store.watch((state, getters) => state.stateAppIsInterested, (newVal, oldVal) => {
alert()
})
}
}
区别是:
- 只要商店发生变化,就会调用
subscribe
回调(在您的情况下,这可能会浪费一些不必要的回调调用)。回调方法接收突变和更新状态作为参数
watch
只会对第一个参数中定义的 getter 的 return 值的变化做出反应,回调接收新值和旧值作为争论。如果需要,您可以观看多个状态。
我正在使用 vue CLI 并创建了多个组件
app.vue
import home_tpl from './home.vue';
new vue({
el : '#app',
components : { home_tpl },
created(){
this.$store.subscribe((mutation) => {
switch(mutation.type){
case 'listing':
alert();
break;
});
}
})
然后我还有一个听众 home.vue
home.vue
export default{
created(){
this.$store.subscribe((mutation) => {
switch(mutation.type){
case 'listing':
alert();
break;
});
}
}
问题是当我 this.$store.commit('listing',1);
这个 this.$store.subscribe((mutation) => {
触发两次时,这是预期的行为,因为我从不同的文件中两次收听事件,有没有办法让它只触发一次每个组件?
我将突变侦听器调用到 home.vue
的原因是因为有一个事件我只想 运行 专门针对该组件。
您的示例代码监听 listing
app.vue
和 home.vue
的变化,但根据您的帖子,他们似乎对不同类型的变化感兴趣?
如评论所述,如果您只对一些更改而不是 所有 商店的更改感兴趣,watch
应该是更好的方法。类似于:
// home.vue
new vue({
el : '#app',
components : { home_tpl },
created(){
this.$store.watch((state, getters) => state.stateHomeIsInterested, (newVal, oldVal) => {
alert()
})
}
})
// app.vue
export default{
created(){
this.$store.watch((state, getters) => state.stateAppIsInterested, (newVal, oldVal) => {
alert()
})
}
}
区别是:
- 只要商店发生变化,就会调用
subscribe
回调(在您的情况下,这可能会浪费一些不必要的回调调用)。回调方法接收突变和更新状态作为参数 watch
只会对第一个参数中定义的 getter 的 return 值的变化做出反应,回调接收新值和旧值作为争论。如果需要,您可以观看多个状态。