【问题标题】: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();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-02
      • 2021-10-22
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 2019-04-05
      • 1970-01-01
      相关资源
      最近更新 更多