Watch 监听

第一种 普通监听

<input type="text" v-model="userName"/> 
data (){
    
    
    return {
    
    
        userName: ''
    }
},
//监听  当userName值发生变化时触发
watch: {
    
    
    userName (newVal,oldVal) {
    
    
        console.log(newVal)
    }
}

第二种 第一种有一个缺点 就是当值第一次绑定的时候 不会执行监听函数,
只有当值改变的时候 才会执行,如果想在第一次绑定的时候执行此监听函数 则需要 设置 immediate: true

<input type="text" v-model="userName"/> 
data (){
    
    
    return {
    
    
        userName: ''
    }
},
watch: {
    
    
    userName: {
    
    
        handler (newVal,oldVal) {
    
    
            console.log(newVal)
        },
        immediate: true
    }
}

第三种深度监听 当要监听对象或数组的时候需要添加deep:true属性

<input type="text" v-model="cityName.name" />
data (){
    
    
    return {
    
    
        cityName: {
    
    name:'北京'}
    }
},
watch: {
    
    
    cityName: {
    
    
        handler(newVal,oldVal) {
    
    
            console.log(newVal)
        },
        immediate: true,
        deep: true
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44640323/article/details/108472186