【问题标题】:can't access "this" inside of component watcher nuxtjs无法访问组件观察器 nuxtjs 中的“this”
【发布时间】:2020-10-09 18:35:07
【问题描述】:
我有一个组件,其状态属性称为“volume”,它绑定到一个滑块元素。我有一个绑定到卷属性的观察者,这样当卷更新时,应该触发一个函数
data () {return {
volume: 0,
}},
methods: {
testMethod () {
console.log("this is firing")
}
},
watch: {
volume: (v) => {
console.log("volume has been updated", v);
this.testMethod();
}
}
运行此代码时,控制台显示错误“无法读取未定义的“testMethod”的属性
我尝试了其他方法,例如访问 $store(这是我最初的问题),但也未能解决。
【问题讨论】:
标签:
vue.js
components
watch
nuxtjs
【解决方案1】:
您不能在 Vue.js 组件(Nuxt 或其他)中使用 fat-arrow 表示法。 fat-arrow 函数定义使用了错误的上下文(在您的情况下为 this),这就是您遇到此问题的原因。
<script>
export default {
data () {return {
volume: 0,
}},
methods: {
testMethod () {
console.log("this is firing")
}
},
watch: {
// Your old code.
// volume: (v) => {
// console.log("volume has been updated", v);
// this.testMethod();
// }
// The corrected way.
volume(v) {
console.log("volume has been updated", v);
this.testMethod();
}
}
};
</script>
【解决方案2】:
您正在使用Arrow Function,它将this 关键字绑定到定义函数的对象,而不是调用函数的对象(在本例中是组件的当前实例)。
改用常规函数语法:
watch: {
volume(v) {
console.log("volume has been updated", v);
this.testMethod();
}
}