vue中watch的handler,deep,immediate用法详解

我们使用watch监听数据时,有三个选项,handler,deep,immediate

handler

我们平时的写法,就默认写的是handler,vue.js会处理这个逻辑,最终编译出来就是这个handler

  watch: {
    // 通过输入框文字的变化,来改变下面的数据
    ipt: {
      handler(newVal,oldVal) {
      	console.log(111)
        if (newVal == "小红") {
          this.name = "小红";
          this.gender = "女";
          this.age = 18;
          this.height = 160;
        } else {
          this.name = "无";
          this.gender = "无";
          this.age = "无";
          this.height = "无";
        }
      },
      immediate:false, //值为true或false,默认false
      deep:false    //值为true或false,默认false
    }
  },
  
  //当immediate和deep都为false时,上下两种写法效果一样
  
    watch:{
	    // 通过输入框文字的变化,来改变下面的数据
	    ipt(val){
	      if(val == '小红'){
	        this.name = '小红'
	        this.gender = '女'
	        this.age = 18
	        this.height = 160
	      }else{
	        this.name = '无'
	        this.gender = '无'
	        this.age = '无'
	        this.height = '无'
	      }
	    }
  },

immediate

该值默认是false,在进入页面时,第一次绑定值,不会立刻执行监听,只有数据发生改变才会执行handler中的操作,我们来输出看一下

immediate为false:

在这里插入图片描述

immediate为true:
我们可以看到,handler会在第一次绑定值时就触发

在这里插入图片描述

deep

vue是不能检测到对象属性的添加或删除,我们使用watch监听一个对象时,除非是直接重新给对象赋值,否则是不能监听到对象里的值的变化的

deep就是用来进行深度监听的!

我们绑定一个对象,修改对象里面的值,看下deep为false时的效果(其实就是毫无效果):

<template>
  <div>
    <div>
      <input type="text" v-model="ipt.text" />
      <p>
        姓名
        <b>{{name}}</b>
      </p>
      <p>
        性别
        <b>{{gender}}</b>
      </p>
      <p>
        年龄
        <b>{{age}}</b>
      </p>
      <p>
        身高
        <b>{{height}}</b>
      </p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "小明",
      gender: "男",
      age: "26",
      height: "180",
      ipt: {
        text:'小明'
      }
    };
  },
  watch: {
    // 通过输入框文字的变化,来改变下面的数据
    ipt: {
      handler(newVal,oldVal) {
        console.log(111)
        if (newVal.text == "小红") {
          this.name = "小红";
          this.gender = "女";
          this.age = 18;
          this.height = 160;
        } else {
          this.name = "无";
          this.gender = "无";
          this.age = "无";
          this.height = "无";
        }
      },
      immediate:false,
      deep:false
    }
  },
  methods: {}
};
</script>

在这里插入图片描述

把deep设为true后,就可以得到我们想要的结果了,可以监听到对象属性的变化

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值