用监视属性实现姓名案例:
<body>
<div id="root">
姓:<input type="text" v-model="firstname"><br/>
名:<input type="text" v-model="lastname"><br/>
全名:<span>{{fullname}}</span>
</div>
</body>
<script>
new Vue({
el:'#root',
data:{
firstname:'张',
lastname:'三',
fullname:'张-三'
},
/*computed:{
fullname(){
return this.firstname+'-'+this.lastname;
}
},*/
watch:{
firstname(newValue,oldValue){
this.fullname=newValue+'-'+this.lastname
},
lastname(newValue,oldValue){
this.firstname=this.firstname+'-'+newValue
}
}
})
</script>
官网上认为,监视属性在该项目上 比不上 计算属性
实现等一秒之后,在修改全名的值:
<body>
<div id="root">
姓:<input type="text" v-model="firstname"><br/>
名:<input type="text" v-model="lastname"><br/>
全名:<span>{{fullname}}</span>
</div>
</body>
<script>
new Vue({
el:'#root',
data:{
firstname:'张',
lastname:'三',
fullname:'张-三'
},
/*computed:{
fullname(){
return this.firstname+'-'+this.lastname;
}
},*/
watch:{
firstname(newValue,oldValue){
//定时器控制的函数不是vue管理的,时间到了是服务器来调用的,所以需要用箭头函数
setTimeout(()=>{
this.fullname=newValue+'-'+this.lastname
},1000)
},
lastname(newValue,oldValue){
this.firstname=this.firstname+'-'+newValue
}
}
})
</script>
此时只能用监听函数。监听函数能够实现异步来维护数据。
总结:
computed和lwatch之向的区別:
1.computed能完成的功能,watch都可以完成。
2.watch能完成的功能。computed不一定能完成。例如:watch可以进行异步操作。
两个重要的小原则:
1.所被vue管理的函数。最好写成普通函数。这样this的指向才是vm 或 组件实的对象。
2.所有不被vue所管理的两数(定时器的回调函数、ajax的回调函数等),最好写成箭头函数。
这样this的指向才是vm 或组件实例对象。