【发布时间】:2019-08-27 02:29:17
【问题描述】:
我正在使用 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 的原因是因为有一个事件我只想专门针对该组件运行。
【问题讨论】:
-
watch不是订阅所有状态更改而只对少数情况做出反应,这里应该更好吗?app.vue和home.vue都应该只关注他们感兴趣的状态变化。 -
@ArieXiao 你能给我看一些代码吗?
-
当你说
trigger only once per component时,这意味着两个订阅组件的两个触发器;但是您的评论表明,无论订阅多少,您都只需要一个触发器。当您只需要一个触发器时,为什么要订阅多个组件? -
@tony19 我必须这样做,因为我有一些仅适用于该特定组件的操作。