之前做vue项目的开发的过程中,遇到在watch中调用methods里面的方法报错问题,今天想起来记录一下
1、问题复现:
<input type="text" v-model="inputValue"/>
export default{
data(){
return {
inputValue: '',
}
},
watch: {
inputValue: (newValue) => {
console.log(newValue);
console.log(this) // undefined
this.getInfo() // 报错
}
},
methods: {
getInfo(){
console.log('这是 getInfo 函数')
}
}
}
2、问题解决: watch中使用箭头函数,导致this是访问不到,需要改成function形式
<input type="text" v-model="inputValue"/>
export default{
data(){
return {
inputValue: '',
}
},
watch: {
inputValue(newValue){
console.log(newValue);
this.getInfo()
}
},
methods: {
getInfo(){
console.log('这是 getInfo 函数')
}
}
}