Vuejs watcher order

亡梦爱人 提交于 2019-12-24 06:35:40

问题


I have a Vue instance with two watchers:

watch: {
    zone:function(zone) {
        console.log('Zone watcher');
        this.route = {};
    },
    route:function(route) {
        console.log('Route watcher');
        if(Object.getOwnPropertyNames(route).length === 0) {
            var _this = this;
            axios.get(route.url).then(function(response) {
                _this.tracks = response.data;
            });
        } else this.tracks = {};
    }
},

When a user selects a zone, route (and tracks) are reset. When user selects a route, tracks are loaded;

I have a component receiving zone and tracks as props, also with two internal watchers that perform some independent actions when any of this props change.

I also have a method that changes both variables:

jump:function(path) {
    var parts = path.split(',');
    this.zone = this.ZONES[parts[0]];
    this.route = this.zone.routes[parts[1]];
},

The problem is watcher for route is fired in first place, then the watcher for zone changes route value triggering its watcher again, reseting tracks value to an empty object.

Is there a way to define the order that watchers must be triggered?


回答1:


Andrey's comment shows the way. This question comes down to which tools you use for what job. Inevitably there's a bit of opinion... watch is for edge cases. You don't need it often, and if you can do without it, you probably should. watch belongs with computed and v-bind: they're reactive, use them (only) for representing state on screen, you have no (or little) control over when they run, and you shouldn't care.

A server request belongs in a method, or in a function outside of Vue (in your store perhaps) where it can be called explicitly. So create yourself a changeZone() function that clears routes and tracks, then calls the server, then updates your data (or store) with the server response. Your code will be much clearer if these little functional sequences are specified explicitly, in one place. The trigger for your sequence should likely be from an event (user-action) or lifecyle hook, not a watch.



来源:https://stackoverflow.com/questions/51155011/vuejs-watcher-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!