Vue侦听器watch的使用与详解

在vue中如果想知道一个值是否发生改变就得用到侦听器watch

第一种用法 如果在vue创建实例是很明确监视谁

<body>
<div id='root'>
  <h2 :class= really ? 'Color:"yellow"' : 'Color:"block"'>字体颜色是{{really}}</h2>
  <button @click = 'changeColor'>切换字体颜色</button>
</div>
</body>
<script>
	const vm = new vue({
		el:'#root',
		data:{
		  really:false
		},
		methods:{
		  changeColor(){
			 this.really = !this.really
			}		
		},
		watch:{
		  really:{
		  	immediate:true, //无论值是否发生改变,时刻都会监听 默认值为false
		     //handler什么时候调用 当really发生改变时
		    handler(newValue,oldValue){
		    console.log('really 发生了改变',newValue,oldValue) //输出   really 发生了改变 true false
		    }
		  }
		}
	})
</script>

第二种用法 如果在vue创建实例是不明确去监视谁

<body>
<div id='root'>
  <h2 :class= really ? 'Color:"yellow"' : 'Color:"block"'>字体颜色是{{really}}</h2>
  <button @click = 'changeColor'>切换字体颜色</button>
</div>
</body>
<script>
	const vm = new vue({
		el:'#root',
		data:{
		  really:false
		},
		methods:{
		  changeColor(){
			 this.really = !this.really
			}		
		},
	})
	vm.$watch('really',{
		    immediate:true, //无论值是否发生改变,时刻都会监听 默认值为false
		  //handler什么时候调用 当really发生改变时
		    handler(newValue,oldValue){
		    console.log('really 发生了改变',newValue,oldValue) //输出   really 发生了改变 true false
	})
</script>

深度监视

<body>
<div id='root'>
  <h2>a的值是:{{number.a}}</h2>
  <button @click = 'number.a++'>a+1</button>
</div>
</body>
<script>
	const vm = new vue({
		el:'#root',
		data:{
		  number:{
		   a:0,
		   b:0,
		  }
		},
	  watch:{
		  number:{
		    deep:true,
		  	immediate:true, //无论值是否发生改变,时刻都会监听 默认值为false
		  //handler什么时候调用 当really发生改变时
		    handler(newValue,oldValue){
		    console.log('really 发生了改变',newValue,oldValue) //输出   really 发生了改变 true false
		    }
		  }
		}
	})
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值