美文网首页
vue之watch

vue之watch

作者: 前端从进阶到入院 | 来源:发表于2022-03-22 00:22 被阅读0次

watch的作用

watch是vue2x中提供的一个options API,它可以帮助我们监听页面中的响应式数据,一旦数据发生了会变就会触发watch中的属性或者方法

watc的形式

  1. 函数形式
    2.对象形式(可以配置深度监听/immediate立即执行)
    3.通过this.$watch调用,通常在生命周期created使用

函数写法

watch: {
  dataForm (newForm,oldForm) {
    ...
  }
}

this调用

created () {
  this.$watch('userInfo.userName',function(newName,oldName) {
    console.log('newName',newName)
  },{
    deep: true,
    immediate: true
  })
}

对象写法

watch: {
  dataForm: {
    deep: true,
    handler: function (newForm,oldForm) {
      ...
    }
  }
}

小栗子

<template>
  <div>
    <h1>{{ userInfo.userName }}</h1>
    <button @click="onUpdateInfo">修改用户细信息</button>
    <br />
    <button @click="onRename">
      只是改变对象中的某一个属性,看watch打印出来的是什么
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {
        userId: 1,
        age: 18,
        userName: "admin",
      },
    };
  },
  created() {
    this.$watch(
      "userInfo.userId",
      function (newId, oldId) {
        console.log("我是通过$watch来监听数据的", newId);
      },
      {
        deep: true,
        immediate: true,
      })
      // 取消监听
     //  onWatch()
  },
  watch: {
    // 无法深度监听
    // userInfo(newInfo, oldInfo) {
    //   console.log("newInfo", newInfo);
    //   console.log("oldInfo", oldInfo);
    // },
    userInfo: {
      deep: true,
      immediate: true,
      handler: function (newInfo, oldInfo) {
        console.log("newInfo", newInfo);
        console.log("oldInfo", oldInfo);
      },
    },
    // 监听某个值的变化
    "userInfo.userName": function (newName, oldName) {
      console.log("newName", newName);
      console.log("oldName", oldName);
    },
  },
  methods: {
    onUpdateInfo() {
      this.userInfo = {
        userId: 2,
        age: 20,
        userName: "superAdmin",
      };
    },
    onRename() {
      this.userInfo.userName = "coderyly";
    },
  },
};
</script>

对象的语法形式可以设置deep属性,对数据进行深度监听

小技巧:

  • 当我们需要监听数组中某个对象的属性时,推荐单独创建一个组件,对组件中最难过的单个值做出监听,这样做的好处是无需deep深度监听,提升性能

相关文章

网友评论

      本文标题:vue之watch

      本文链接:https://www.haomeiwen.com/subject/jsbxjrtx.html