Vue中watch(监听)简单用法解读

Vue中watch(监听)简单用法解读

编程文章jaq1232025-03-25 11:53:4527A+A-
<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>


点击这里复制本文地址 以上内容由jaq123整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

苍茫编程网 © All Rights Reserved.  蜀ICP备2024111239号-21