【问题标题】:Why on vue 3 watch is not called on object mutation?为什么在 vue 3 watch 上不调用对象突变?
【发布时间】:2021-05-30 09:18:37
【问题描述】:

你能解释一下为什么当我在 Vue 3 中改变对象时没有调用watch。 相反,我需要完全替换对象。

https://codesandbox.io/s/nostalgic-glade-zer8v?file=/src/components/HelloWorld.vue

  methods: {
    change() {
      // Triggers watch
      this.user = { ...this.user, name: "hello" };
      // Doesn't triger watch
      this.user.name = "hello";
    },
  },

  watch: {
    user(nextUser) {
      console.log(nextUser);
    },
  },

【问题讨论】:

    标签: javascript vue.js vue-component vuejs3 vue-reactivity


    【解决方案1】:

    来自watch docs

    要同时检测对象内部的嵌套值变化,您需要在选项参数中传入deep: true

    使用具有handler 方法的watch object syntax,并使用deep 属性:

    watch: {
      user: {                        // Watch object syntax
        handler(nextUser) {          // method must be called `handler`
          console.log(nextUser);
        },
        deep: true                   // deep watch for nested property changes
      },
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 2021-05-09
      • 2021-07-13
      • 2019-07-22
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      相关资源
      最近更新 更多