<script src="http://cdn.staticfile.org/vue/2.6.10/vue.js"></script>
{{name}}
{{obj.id}}
<script>
var vm=new Vue({
el:'#app',
data:{
name:'jiajia',
age:20,
obj:{id:10,city:'北京'}
},
methods:{
monitor:function(newValue,oldValue){
console.log('name被修改了',newValue,oldValue)
}
},
watch: {
// name:function(newValue,oldValue){ //局部定义
// console.log('name被修改了',newValue,oldValue)
// },
//监听几种不同的写法
// 'name'(newValue,oldValue){
// console.log('name被修改了',newValue,oldValue)
// },
// name(newValue,oldValue){
// console.log('name被修改了',newValue,oldValue)
// },
name:'monitor', //值可以是方法
//监听对象
// 'obj.id'(newValue,oldValue){ //监听对象中单一属性
// console.log('id被修改了',newValue,oldValue)
// },
// 'obj'(newValue,oldValue){ //不能触发
// console.log('id被修改了',newValue,oldValue)
// },
//深度监听
obj:{
handler:function(newValue,oldValue){ //监听中的默认的执行函数
console.log('obj修改了',newValue,oldValue) //监听的是数组或对象 newValue,oldValue是相等的,因为指向的是同一个对象
},
deep:true //监听对象的属性变化,false时 handler函数不执行,只有当true时,handler才会执行
}
}
});
//全局方式
// vm.$watch('name',function(newValue,oldValue){
// console.log('name被修改了',newValue,oldValue)
// })
</script>