关键词搜索

源码搜索 ×
×

Vue 监视属性

发布2023-04-14浏览288次

详情内容

Vue 监视属性

当被监视的属性变化时,回调函数handler()自动调用,进行相关操作
监视的属性必须存在,才能进行监视
监视的两种方法:
(1).new Vue时传入watch配置
(2)通过vm.$watch监视

<body>
	<div id="root">
		<h2>今天的天气很{{info}}</h2>
		<button @click="changeWeather">切换天气</button>
	</div>
</body>

<script>
	new Vue({
		el:"#root",
		data:{
			isHot:true
		},
		methods:{
			changeWeather(){
				 this.isHot = !this.isHot
			}
		},
		computed:{
			info(){
				return this.isHot ? '炎热' : '凉爽'
			}
		},
		watch:{
			isHot:{
				//初始化时让handler调用一下
				immediate:true,
				//handler什么时候调用?当isHot发生改变时
				//newValue是修改后的值,oldValue修改前的值
				handler(newValue,oldValue){
					
				}
			}
		}
	})
</script>

    另一种办法

    vm.$watch('isHot',{
    	immediate:true,
    	handler(newValue,oldValue){
    					
    	}
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    深度监视

    deep:true

    <body>
    	<div id="root">
    		<h2>{{number.a}}</h2>
    		<button @click="number.a++">a+1</button>
    	</div>
    </body>
    
    <script>
    	new Vue({
    		el:"#root",
    		data:{
    			number:{
    				a:100
    				b:200		
    			}
    		},
    		watch:{
    			number:{
    				deep:true,
    				handler(){
    					console.log('number改变了');
    				}
    			}
    		}
    	})
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    监视属性简写

    当所监视的属性只需要handler时,我们就可以使用简写形式

    watch:{
    	number(newValue,oldValue){
    		console.log('123')
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    另一种配置监视属性的方法

    vm.$watch('number',{
    	immediate:true,
    	deep:true,
    	handler(newValue,oldValue){
    		console.log('abc');
    	}
    })
    
    //简写
    vm.$watch('isHot',function(newValue,oldValue){
    	console.log('abc')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    相关技术文章

    点击QQ咨询
    开通会员
    返回顶部
    ×
    微信扫码支付
    微信扫码支付
    确定支付下载
    请使用微信描二维码支付
    ×

    提示信息

    ×

    选择支付方式

    • 微信支付
    • 支付宝付款
    确定支付下载