繁体   English   中英

vue.js 手表未更新

[英]vue.js watch not updated

我是 vue 的新手。 我现在正在尝试根据另一个计算变量的变化来更新几个变量。

这个计算变量从 Vuex 存储中获取值并按预期工作。 我看到价值观发生了变化。 为了计算派生变量,我创建了一个监视计算变量然后更新这些派生值的手表。 此手表在启动期间被调用两次,然后不再调用,尽管计算值不断更新。 我究竟做错了什么。

这是有效的:

...
computed: {
    lastAndMarkPrice() {
      return store.getters.getLastAndMarkPriceByExchange(
        "deribit",
        store.getters.getAsset
      );
    },
...

这部分不起作用:

...
data: () => ({
    lastPriceUp: false,
    lastPriceDn: false,
    markPriceUp: false,
    markPriceDn: false,
  }),
...
watch: {
    lastAndMarkPrice (newValue, oldValue) {
      console.log(newValue, oldValue);
      this.lastPriceUp = newValue.lastPrice > oldValue.lastPrice;
      this.lastPriceDn = newValue.lastPrice < oldValue.lastPrice;
      this.markPriceUp = newValue.markPrice > oldValue.markPrice;
      this.markPriceDn = newValue.markPrice < oldValue.markPrice;
    },
  },
...

默认情况下, watch是浅的。 如果将新的 object 分配给lastAndMarkPrice ,则将调用处理程序,但它不会检查该 object 中的属性突变。

要创建一个深度观察者,您需要执行以下操作:

watch: {
  lastAndMarkPrice: {
    deep: true,

    handler (newValue, oldValue) {
      // ...
    }
  }
}

https://v2.vuejs.org/v2/api/#watch

通常这将是正确的解决方案,但您的用例稍微复杂一些,因为您需要访问旧值。 使用深度观察器对此无济于事,因为您只会通过相同的 object。

为了解决这个问题,您需要在某处复制旧值,以便您仍然可以将它们与新值进行比较。 一种方法是让计算属性获取副本:

computed: {
  lastAndMarkPrice() {
    const prices = store.getters.getLastAndMarkPriceByExchange(
      "deribit",
      store.getters.getAsset
    );

    // I'm assuming that prices is initially null or undefined.
    // You may not need this bit if it isn't.
    if (!prices) {
      return null;
    }

    return {
      lastPrice: prices.lastPrice,
      markPrice: prices.markPrice
    }
  }
}

使用上面的代码,每次lastPricemarkPrice的值发生变化时,它都会重新运行计算属性并创建一个新的 object。 这将触发watch处理程序,重要的是,您将获得两个不同的对象作为旧值和新值传递。 在这种情况下,您不需要使用deep ,因为 object 本身正在发生变化,而不仅仅是其中的属性。

你也可以用...缩短一点

return { ...prices }

...而不是显式地复制这两个属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM