Vue2中watch侦听器

watch侦听器作用


定义一个对象来创建监听器。这个对象包含要监听的数据属性名称及其对应的回调函数。通过监听器来监听对象,来实现数据的前后变化的强制同步。

基础用法


  • 方式1
<template>
    <div class="test">
      姓名:<el-input v-model="userName" style="width:30%;" size="medium"></el-input>
    </div>
</template>
    
<script>
  export default {
    components: {},
    name: "test",
    data() {
      return {
        userName: "张三",
      };
    },
    watch: {
      userName(newVal, oldVal) {
        console.log("newVal = " + newVal);
        console.log("oldVal = " + oldVal);
      }
    },
    mounted() {},
    beforeCreate() {},
    created() {},
    methods: {},
  };
</script>
<style scoped></style>
  • 方式2
watch: {
  userName : {
    handler(newVal, oldVal) {
      console.log("newVal = " + newVal);
      console.log("oldVal = " + oldVal);
    }
  }
},

immediate用法


  • immediate属性为true时,一直都会监听。
  • immediate属性为false时,默认用法,值发生改变才监听。
<template>
    <div class="test">
      姓名:<el-input v-model="userName" style="width:30%;" size="medium"></el-input>
    </div>
</template>
    
<script>
  export default {
    components: {},
    name: "test",
    data() {
      return {
        userName: "张三",
      };
    },
    watch: {
      userName : {
        handler(newVal, oldVal) {
          console.log("newVal = " + newVal);
          console.log("oldVal = " + oldVal);
        },
        immediate: true
      }
    },
    mounted() {},
    beforeCreate() {},
    created() {},
    methods: {},
  };
</script>
<style scoped></style>

监听对象和数组情况


监听对象

  • deep属性值为true时,监听对象整个内部的属性;
  • deep属性值为false时,则监听不到对象整个内部的属性。
<template>
    <div class="test">
      地址:<el-input v-model="tempUserObj.info.address" style="width:30%;" size="medium"></el-input>
    </div>
</template>
    
<script>
  export default {
    components: {},
    name: "test",
    data() {
      return {
        tempUserObj: {
          "id" : "123456",
          "family" : ["father", "sister", "brother"],
          "info" : {
            "age" : 30,
            "address" : "吉林省长春市朝阳区"
          },
        },
      };
    },
    watch: {
      tempUserObj : {
        handler(newVal, oldVal) {
          console.log("newVal = " + JSON.stringify(newVal));
          console.log("oldVal = " + JSON.stringify(oldVal));
        },
        immediate: true,
        deep: true
      }
    },
    mounted() {},
    beforeCreate() {},
    created() {},
    methods: {},
  };
</script>
<style scoped></style>

监听数组

watch: {
  familyArr : {
    handler(newVal, oldVal) {
      console.log("newVal = " + JSON.stringify(newVal));
      console.log("oldVal = " + JSON.stringify(oldVal));
    },
    deep: true
  }
},
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容