<div id="app">
<input v-model="firstName" />
<input v-model="lastName" />
<p>全名: {{ fullname }}</p>
</div>
computed实现计算全名
var vm = new Vue({
el: '#app',
data: {
firstName: '周',
lastName: '瑜'
},
computed: {
fullname(){
return this.firstName + this.lastName
}
},
watch:{
fullname(newValue){
setTimeout(()=>{
console.log(newValue)
},1000)
}
}
})
- computed可以定义新的属性,如fullname;
- computed依赖return返回值;
- computed不能开启异步任务去维护数据;
watch实现计算全名
var vm = new Vue({
el: '#app',
data: {
firstName: '',
lastName: '',
fullName: ''
},
watch:{
firstName(newValue,oldValue){
setTimeout(()=>{
this.fullName = newValue + this.lastName
},1000)
},
lastName(newValue,oldValue){
this.fullName = this.firstName + newValue
}
}
})
- 此例中watch监听firstName、lastName的变化去合成fullName,但是 fullName属性需要在data里面先声明;
- watch监听可以开启异步任务,不需要return返回值;
- watch可以配置immdeitate(立即监听)、deep(深度监视)等;
- 在上一例中表明watch不仅可以监听data里面的属性,也可以监听computed里面定义的fullName属性;