can't access "this" inside of component watcher nuxtjs

Viewed 2457

I have a component with a state property called "volume" which is bound to a slider element. I have a watcher bound to the volume property such that when the volume is updated, a function should fire

data () {return {
  volume: 0, 
}},

 methods: {
  testMethod () {
    console.log("this is firing")
  }
 },

watch: {
  volume: (v) => {
    console.log("volume has been updated", v);
    this.testMethod();
  }
}

On running this code, the console shows the error "Cannot read property of "testMethod" of undefined

I have tried other things like accessing the $store (which was my initial issue), and that is failing to resolve too.

2 Answers

You can't use the fat-arrow notation within a Vue.js component (Nuxt or otherwise). The fat-arrow function definition uses the wrong context (this in your case), which is why you are running into this problem.

<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>

You are using an Arrow Function, which binds the this keyword to the object that defines the function, rather than the object that called the function (which is the current instance of the component in this case).

Use regular function syntax instead:

watch: {
  volume(v) {
    console.log("volume has been updated", v);
    this.testMethod();
  }
}
Related