【发布时间】:2019-03-09 07:51:21
【问题描述】:
我正在 VueJS 中为我正在制作的应用程序创建一个组件,当我的 var 更改时,它有一些观察者将逻辑应用于组件的其他部分。一旦组件被初始化,它仍然需要通过用户通过 Axios 完成的一些事件后来自服务器的一些数据来设置。此数据从主应用程序发出的事件中获取到组件。现在问题是这个 var 通常会发生变化(并非总是如此),但我不希望第一次应用这个逻辑,所以我决定设置一个标志并在观察者中检查它是否返回,但它没有发生:一旦我将该标志设置回真(它检查!this.flag),观察者就会被触发。代码如下:
data(){
return {
isSet: false,
myVar: {
first: 0,
second: 0
}
}
},
watch: {
'myVar.first': {
handler: function(newVal, oldVal){
if(!this.isSet || other.condition){return}
console.log('first triggered');
},
immediate: false
},
'myVar.second': {
handler: function(newVal, oldVal){
if(!this.isSet || other.condition){return}
console.log('second triggered');
},
immediate: false
}
},
methods: {
setBus(){ // gets called on created(){}
let self = this;
Bus.$on('my-event', function(c){
self.doFirstSet(c);
});
},
doFirstSet(c){
// do other setting
if(c.someCondition){
this.doExtraConfig(c);
}
this.isSet = true; // at this point is when the watchers get triggered
},
doExtraConfig(c){
// do more stuff
if('first' in c){
this.myVar.first = c.first;
}else if('second' in c){
this.myVar.second = c.second;
}
console.log("watchers don't get triggered yet");
}
}
知道如何在标志更改时阻止它们发射吗?
【问题讨论】:
标签: vuejs2 vue-component watch