Vue/ Nuxt - mounted: () => Vs mounted: function()

Viewed 17183

Why the results are different for using () => and function() in mounted:

export default {
  mounted: () => {
    this.socket = 'something'
    console.log('mounted')
  },
  methods: {
    submitMessage() {
      console.log(this.socket) // undefined
    }
  }
}

Using function():

export default {
  mounted: function() {
    this.socket = 'something'
    console.log('mounted')
  },
  methods: {
    submitMessage() {
      console.log(this.socket) // something
    }
  }
}

Any ideas?

1 Answers

You should not use an arrow function to define a lifecycle hook, methods ,... (e.g. mounted: () => this.socket++). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.socket will be undefined.

Related