Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue watch 如何监听一个对象内部的变化(deep) - 掘金 #210

Open
xiaodongxier opened this issue Sep 8, 2023 · 0 comments
Open

Comments

@xiaodongxier
Copy link
Owner

监听某个属性

如果只是监听对象的某个属性的话,可以使用字符串的形式监听属性 (对象.属性名)

<template>
  <div class="watch">
    <button @click="changeName">修改obj.name</button>
    <input type="text" v-model="obj.name" />
    <button @click="changeSex">修改obj.sex</button>
    <input type="text" v-model="obj.sex" />
  </div>
</template>
<script>
export default {
  data() {
    return {
      obj: {
        name: "温情",
        sex: "男",
      },
    };
  },
  watch: {
    "obj.name": {
      handler(newValue, oldValue) {
        console.log("obj 的 name 发生了变化");
        console.log('newValue: ' + newValue);
        console.log('oldValue: ' + oldValue);
      },
    },
  },
  methods: {
    changeName() {
      this.obj.name += "1";
    },
    changeSex() {
      this.obj.sex += "1";
    },
  },
};
</script>

需要注意得到是 handler 是固定写法,不能用其他的。

深度监听

  • 当需要监听一个对象的改变时,普通的watch方法无法监听到对象内部属性的改变,此时需要deep属性对对象进行深度监听
  • 修改一下 watch 里面的代码,其他代码全和上面一样
watch: {
    obj: {
      handler(newValue, oldValue) {
        console.log("obj 发生了变化");
      },
      deep: true,
      immediate: true,
    },
},

immediate 表示在 watch 中首次绑定的时候,是否执行 handler,值为 true 则表示在 watch 中声明的时候,就立即执行 handler 方法,值为 false,则和一般使用 watch 一样,在数据发生变化的时候才执行handler。 上面 gif 图 之所以刷新马上就执行了 handler 函数,就是因为设置了 immediate 属性为 true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant