文章目录
- 监听器语法
- watch、computed、methods的对比
- 监听器应用
一、监听器语法
watch:{
msg:function(newVal,oldval){
console.log(newVal,oldval);
console.log(this.msg);
},
obj:{
deep:true,
handler:function(new_val,old_val){
console.log(new_val,old_val);
}
}
二、watch、computed、methods的对比
1、watch和computed都是以Vue的依赖追踪机制为基础的
2、methods里面是用来定义函数的
watch:{ firstname:function(val){ this.fullname=val+''+this.lastname }, lastname:function(val){ this.fiullname=firstname+''+val } }, computed:{ fullname:{ get:function(){ return this.firstname+''+this.lastname; }, set:function(newValue){ let name=newValue.split(''); this.firstname=name[0]; this.lastname=name[name.length - 1] } } }
三、监听器应用-距离转换器
let app =new Vue({
el:"#app",
data:{
km:10,
m:1
},
methods:{
kmtom:function(val){
this.m=this.km*1000;
},
mtokm:function(val){
this.km=this.m/1000;
}
},
watch:{
km:'kmtom',
m:'mtokm'
}
})