Vuejs 观察者顺序 [英] Vuejs watcher order

查看:28
本文介绍了Vuejs 观察者顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个观察者的 Vue 实例:

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;

我有一个组件接收 zonetracks 作为道具,还有两个内部观察者,当这些道具中的任何一个发生变化时,它们会执行一些独立的操作.

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]];
},

问题是 route 的观察者首先被触发,然后 zone 的观察者改变 route 值再次触发它的观察者,重置跟踪值到一个空对象.

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?

推荐答案

Andrey 的评论指明了方向.这个问题归结为您为什么工作使用哪些工具.不可避免地会有一些意见...... watch 用于边缘情况.你并不经常需要它,如果你可以不用它,你可能应该这样做.watch 属于计算和 v-bind:它们是反应性的,使用它们(仅)来表示屏幕上的状态,您无法(或几乎)控制它们何时运行,您不应该关心.

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.

服务器请求属于 Vue 之外的方法或函数(可能在您的商店中)可以显式调用.因此,为自己创建一个 changeZone() 函数,该函数清除路线和轨迹,然后调用服务器,然后使用服务器响应更新您的数据(或存储).如果在一处显式指定这些小功能序列,您的代码将更加清晰.序列的触发器应该来自事件(用户操作)或生命周期钩子,而不是手表.

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.

这篇关于Vuejs 观察者顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆