vue.js - Vuex 变异订阅触发多次
问题描述
我正在使用 vue CLI,并创建了多个组件
应用程序.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 的听众
家.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 的返回值的更改做出反应,并且回调接收新值和旧值作为参数。如果需要,您可以查看多个状态。
推荐阅读
- javascript - 为什么屏幕上只显示最后一个输入值?
- c++ - vector.empty() 如何工作?
- swiftui - 如何通过变量更改(绑定)触发函数
- python - 如何根据python中的常见项目对列表项进行分组
- symfony - Symfony 序列化器和多对多设置器
- ios - 当我尝试使用 Apple 登录时,我将 Email 和 FullName 设为 nil 值
- reactjs - 如何在反应中以多步形式将图像src添加到状态
- automated-tests - 线程“主”quickfix.ConfigError 中的异常:FIX44.xml:无法解析数据字典文件
- flutter - Flutter - 如何使用自定义前缀设计制作自定义输入字段?
- azure - 如何下载 Python 中的 Azure Bot 源代码?