我正在使用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
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返回值的更改做出反应,并且回调会将新值和旧值作为参数接收。如果需要,您可以观看多个状态。