vue中同時監聽多個參數

vue使用watch同時監聽多個參數,其中有任意一個參數發生改變時,都會被監聽到

需要使用到計算屬性computed監聽watch

data中定義一個對象:

data(){
    return{
        obj:{
            name:'xpf',
            gender:'male',
            age:24
	}
    }
}

computed中:將需要監聽的參數放入一個新變量中

computed:{
    'newParams':function(){
        const {name,age} = this.obj
        return {name,age}
    }	
},

watch中:監聽新的變量

watch:{
    newParams:function(){
        alert(1)
    }
},

完整代碼:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>watch同時監聽多個屬性</title>
	<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
</head>
<body>
	<div id="app">
		<div @click="changeObj">點我</div>
	</div>	
	<script>
		new Vue({
			el:'#app',
			data(){
				return{
					obj:{
						name:'xpf',
						gender:'male',
						age:24
					}
				}
			},
			computed:{
				'newParams':function(){
					const {name,age} = this.obj
					return {name,age}
				}	
			},
			watch:{
				newParams:function(){
					alert(1)
				}
			},
			methods:{
				changeObj(){
					// this.obj.name = 'xx'
					this.obj.age = 21
				}
			}
		})
	</script>
</body>
</html>

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章