解决vue侦听器watch,调用this时出现undefined
2022-11-19 本文已影响0人
扶得一人醉如苏沐晨
watch: {
'detailData.swcarno': (val) => {
const upperCase = val.toUpperCase()
this.detailData.swcarno = upperCase
}
},
这里控制台报错
TypeError: Cannot read properties of undefined (reading 'detailData')
这里报错undefined,这里错误的原因是不能写成箭头函数。写成箭头函数后,this会取上下文,而不是组件里面的this了,正确写法为:
watch: {
'detailData.swcarno': function (val) {
const upperCase = val.toUpperCase()
this.detailData.swcarno = upperCase
}
},