微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么在 vue 3 watch 上没有调用对象突变?

如何解决为什么在 vue 3 watch 上没有调用对象突变?

你能解释为什么当我在 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);
    },

解决方法

来自watch docs

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

使用具有 watch 方法的 handler 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
  },}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。