一、watch用法:
1、基础写法
<div>
<p>FullName: {
{fullName}}</p>
<p>FirstName: <input type="text" v-model="firstName"></p>
</div>
new Vue({
el: '#root',
data: {
firstName: 'Dawei',
lastName: 'Lou',
fullName: ''
},
watch: {
firstName(newName, oldName) {
this.fullName = newName + ' ' + this.lastName;
}
}
})
上面的代码的效果是,当我们输入firstName
后,wacth
监听每次修改变化的新值,然后计算输出fullName
。
2、handler方法和immediate属性
例1 watch 的一个特点是,最初绑定的时候是不会执行的,要等到 firstName
改变时才执行监听计算,如果需要最初绑定的时候也执行:
watch: {
firstName: {
handler(newName, oldName) {
this.fullName = newName + ' ' + this.lastName;
},
// 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法