0

I want to access an object of a component, but this in methods is references to the methods: {} object.

methods: {
  getInput: () => {
    return this.$refs.input.value
  }
}

I tried to invoke getInput(), but I am getting an error:

Uncaught TypeError: Cannot read property '$refs' of undefined.

How can I access an object of a component instead of a methods object?

Vega TV
  • 217
  • 2
  • 10

1 Answers1

4

According to official docs You should use normal function instead of arrow one in order to get access to the component instance :

    methods: {
      getInput() {
        return this.$ref.input.value 
      }
    }

Note that you should not use an arrow function to define a method (e.g. plus: () => this.a++). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.a will be undefined.

tony19
  • 125,647
  • 18
  • 229
  • 307
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164