實例詳解vue.js淺度監(jiān)聽和深度監(jiān)聽及watch用法
更新時間:2018年08月16日 11:06:20 作者:愛吃排骨
這篇文章主要介紹了vue.js淺度監(jiān)聽和深度監(jiān)聽及watch用法,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友參考下吧
第一個淺度監(jiān)聽:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="app">
<p>{{a}}</p>
<p>{}</p>
</div>
<script>
var vm=new Vue({
el:"#app",
data:{
a:10,
b:15
}
});
vm.$watch("a",function(){
alert('a變化了');
this.b=100;
});
document.onclick=function(){
vm.a=2
}
</script>
</body>
</html>
第二個深度監(jiān)聽
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/vue.js"></script>
</head>
<body>
<div id="app">
<p>{{a|json}}</p>
<p>{}</p>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
a: { id: "1", title: "width" },
b: 15
}
});
vm.$watch("a", function() {
alert('a變化了');
this.b = 100;
}, { deep: true });
document.onclick = function() {
vm.a.id = "2";
}
</script>
</body>
</html>
ps:下面看下vue中watch用法
對應(yīng)一個對象,鍵是觀察表達式,值是對應(yīng)回調(diào)。值也可以是方法名,或者是對象,包含選項。在實例化時為每個鍵調(diào)用 $watch() ;
//使用官方vue-cli腳手架書寫
<template>
//觀察數(shù)據(jù)為字符串或數(shù)組
<input v-model="example0"/>
<input v-model="example1"/>
/當單觀察數(shù)據(jù)examples2為對象時,如果鍵值發(fā)生變化,為了監(jiān)聽到數(shù)據(jù)變化,需要添加deep:true參數(shù)
<input v-model="example2.inner0"/>
</template>
<script>
export default {
data(){
return {
example0:"",
example1:"",
example2:{
inner0:1,
innner1:2
}
}
},
watch:{
example0(curVal,oldVal){
console.log(curVal,oldVal);
},
example1:'a',//值可以為methods的方法名
example2:{
//注意:當觀察的數(shù)據(jù)為對象或數(shù)組時,curVal和oldVal是相等的,因為這兩個形參指向的是同一個數(shù)據(jù)對象
handler(curVal,oldVal){
conosle.log(curVal,oldVal)
},
deep:true
}
},
methods:{
a(curVal,oldVal){
conosle.log(curVal,oldVal)
}
}
}
</script>
相關(guān)文章
Vite+TS+Vue開啟eslint和prettier規(guī)范及校驗方式
這篇文章主要介紹了Vite+TS+Vue開啟eslint和prettier規(guī)范及校驗方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
vue3中配置文件vue.config.js不生效的解決辦法
這篇文章主要介紹了vue3中配置文件vue.config.js不生效的解決辦法,文中通過代碼示例講解的非常詳細,對大家解決問題有一定的幫助,需要的朋友可以參考下2024-05-05
vue(element ui)使用websocket及心跳檢測方式
這篇文章主要介紹了vue(element ui)使用websocket及心跳檢測方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07

