Lor*_*rza 2 components watch vue.js nuxtjs
我有一个带有名为“volume”的状态属性的组件,它绑定到滑块元素。我有一个绑定到卷属性的观察程序,这样当更新卷时,应该触发一个函数
data () {return {
volume: 0,
}},
methods: {
testMethod () {
console.log("this is firing")
}
},
watch: {
volume: (v) => {
console.log("volume has been updated", v);
this.testMethod();
}
}Run Code Online (Sandbox Code Playgroud)
运行此代码时,控制台显示错误“无法读取未定义的“testMethod”属性”
我尝试过其他方法,例如访问 $store (这是我最初的问题),但也未能解决。
您不能fat-arrow在 Vue.js 组件(Nuxt 或其他组件)中使用该表示法。函数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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3334 次 |
| 最近记录: |