【问题标题】:vue.js watch not updatedvue.js 手表未更新
【发布时间】:2020-11-08 20:46:20
【问题描述】:

我是 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;
    },
  },
...

【问题讨论】:

  • 是对象本身改变还是仅仅改变了其中价格属性的值?

标签: javascript vue.js vuex vuetify.js


【解决方案1】:

默认情况下,watch 是浅的。如果一个新对象被分配给lastAndMarkPrice,那么处理程序将被调用,但它不会检查该对象内属性的变化。

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

watch: {
  lastAndMarkPrice: {
    deep: true,

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

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

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

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

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

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

return { ...prices }

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

【讨论】:

    猜你喜欢
    • 2019-06-12
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 2020-07-04
    • 2017-07-29
    • 2018-08-08
    • 1970-01-01
    相关资源
    最近更新 更多