This time I will bring you the instructions for using the Vue data monitoring watch. What are the precautions for using the Vue data monitoring watch? The following is a practical case, let's take a look.
When the data in the Vue view changes, the associated function will be executed
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <!DOCTYPE html>
<html lang= "en" >
<head>
<meta charset= "UTF-8" >
<title>监听方法watch的使用</title>
<script src= "https://cdn.bootcss.com/vue/2.5.16/vue.js" ></script>
</head>
<body>
<p id= "root" ></p>
<script>
var vm = new Vue({
el: "#root" ,
data: { obj: {name: "zhaoolee" , age: 12} , tel:6666666},
template: `<p><p>姓名: {{obj.name}}</p>
<p>电话: {{tel}}</p>
<input type= "text" v-model= "obj.name" >
<input type= "text" v-model= "tel" ></p>`,
watch: {
obj: {
handler(){
console.log( "obj被改变" );
},
immediate: true,
deep: true
},
"obj.name" : {
handler(){
console.log( "=>obj.name被改变" );
}
},
tel:{
handler(){
console.log( "tel被改变" );
}
}
}
})
</script>
</body>
</html>
|
Copy after login
Corresponds to an object, the key is observation
Expression, the value is the corresponding callback. The value can also be a method name, or an object containing options. Call $watch() for each key during instantiation;
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <template>
<input v-model= "example0" />
<input v-model= "example1" />
/当单观察数据examples2为对象时,如果键值发生变化,为了监听到数据变化,需要添加deep:true参数
<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' ,
example2:{
handler(curVal,oldVal){
conosle.log(curVal,oldVal)
},
deep:true
}
},
methods:{
a(curVal,oldVal){
conosle.log(curVal,oldVal)
}
}
}
</script>
|
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
js implements front-end and back-end transfer of Json code to each other
How does Vue operate the html field string and convert it to HTML tag
The above is the detailed content of Vue data monitoring watch usage instructions. For more information, please follow other related articles on the PHP Chinese website!