VueJS - Skip watcher's first change

2019-08-07 05:18发布

I'm creating a component in VueJS for an app I'm making, it has some watchers to apply logic to other parts of the component when my var changes. Once the component is initialized, it still needs to be set by some data from the server coming after a few events done by the user via Axios. This data gets to the component from an event emmited by the main app. Now the thing is that this var usually changes (not always), but I don't want that logic to be applied this first time, so I decided to set a flag and check it in the watcher to return , but it's not happening: as soon as I set that flag back to true (it checks for !this.flag), the watcher gets triggered anyways. Here's the code:

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");
    }
}

Any idea of how to stop them to fire when the flag changes?

1条回答
Luminary・发光体
2楼-- · 2019-08-07 05:48

You should simply declare a Boolean Variable which defines if your data fetching is done. By default you set it to false doneFetching: false and once your fetching Logic is done you call this.doneFetching = true.

After that all you have to do in your watcher is a clean and simply if(this.doneFetching){...} This simple logic should prevent your watcher logic to get triggered before you want it.

查看更多
登录 后发表回答