2

我有一个带有名为“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 (这是我最初的问题),但也未能解决。

4

2 回答 2

5

您不能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>

于 2020-06-19T13:35:59.563 回答
1

您正在使用箭头函数,它将关键字绑定this到定义函数的对象,而不是调用函数的对象(在这种情况下是组件的当前实例)。

改用常规函数语法:

watch: {
  volume(v) {
    console.log("volume has been updated", v);
    this.testMethod();
  }
}
于 2020-06-19T13:38:57.200 回答