VueJs $watch()方法總結!!
阿新 • • 發佈:2019-01-07
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="childrens.name"/>
<input type="text" v-model="lastName"/>
</div>
</body>
<script type="text/javascript">
var vm = new Vue( {
el: '#app',
data: {
childrens: {
name: '小強',
age: 20,
sex: '男'
},
tdArray:["1","2"],
lastName:"張三"
},
watch:{
childrens:{
handler:function(val,oldval){
console.log(val.name)
},
deep:true//物件內部的屬性監聽,也叫深度監聽
},
'childrens.name':function(val,oldval){
console.log(val+"aaa")
},//鍵路徑必須加上引號
lastName:function(val,oldval){
console.log(this.lastName)
}
},//以V-model繫結資料時使用的資料變化監測
} );
vm.$watch("lastName",function(val,oldval){
console.log(val)
})//主動呼叫$watch方法來進行資料監測</span>
</script>
</html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="childrens.name"/>
<input type="text" v-model="lastName"/>
</div>
</body>
<script type="text/javascript">
var vm = new Vue( {
el: '#app',
data: {
childrens: {
name: '小強',
age: 20,
sex: '男'
},
tdArray:["1","2"],
lastName:"張三"
},
watch:{
childrens:{
handler:function(val,oldval){
console.log(val.name)
},
deep:true//物件內部的屬性監聽,也叫深度監聽
},
'childrens.name':function(val,oldval){
console.log(val+"aaa")
},//鍵路徑必須加上引號
lastName:function(val,oldval){
console.log(this.lastName)
}
},//以V-model繫結資料時使用的資料變化監測
} );
vm.$watch("lastName",function(val,oldval){
console.log(val)
})//主動呼叫$watch方法來進行資料監測</span>
</script>
</html>