一、watch的直接监听
//1、简单变量的监听
export default {
data(){
return {
inputValue: '',
watchInputValue: ''
}
},
watch: {
inputValue(newName, oldName){
this.watchInputValue = newName
}
}
}
//2、对象中变量的监听
export default {
data(){
return {
info: {
name: ''
},
}
},
watch: {
'info.name'(newName, oldName){
console.log(newName);
}
}
}
//3、监听值为处理函数
export default {
data(){
return {
inputValue: '',
watchInputValue: ''
}
},
watch: {
inputValue: 'watchInputNameFunc' // 也可以写成: 'inputValue': 'watchInputNameFunc'
},
methods: {
watchInputNameFunc(newName, oldName){
console.log(newName) // this.inputValue的值
this.watchInputValue = this.inputValue // 也可以写成:this.watchInputValue = newName
},
}
}
二、watch的handler函数监听
//1、简单变量的监听(handler函数监听)
export default {
data(){
return {
inputValue: '',
watchInputValue: ''
}
},
watch: {
inputValue:{
handler(newName, oldName){
this.watchInputValue = newName
}
}
}
}
//2、对象中变量的监听(handler函数+deep属性监听)
export default {
data(){
return {
info: {
name: ''
},
}
},
watch: {
info:{
handler(newName, oldName){
console.log('info对象中name属性值为:' + this.info.name)
},
deep: true
}
}
}
//2.2当对象的属性过多时,使用deep属性直接对对象进行深度监听,会给所有的属性加上监听器。
如果你只是想对对象中的其中一个属性进行监听,那么可以直接使用字符串形式的监听
watch(){
'对象.属性'(newValue, oldValue){
consle.log(newValue, oldValue)
}
}
//3、变量的初始化监听(handler函数+immediate) 不使用immediate:true,那么变量在响应式系统中的第一次初始化值是监听不到的
export default {
data(){
return {
inputValue: '11111',
watchInputValue: ''
}
},
watch: {
inputValue:{
handler(newName, oldName){
this.watchInputValue = newName
},
immediate: true
}
}
}