gpt4 book ai didi

vue.js - 无法访问组件观察器 nuxtjs 内部的 "this"

转载 作者:行者123 更新时间:2023-12-01 21:30:51 25 4
gpt4 key购买 nike

我有一个组件,它有一个名为“volume”的状态属性,它绑定(bind)到一个 slider 元素。我有一个绑定(bind)到 volume 属性的观察者,这样当 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 组件(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>

关于vue.js - 无法访问组件观察器 nuxtjs 内部的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62471392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com