Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 826
Run Avatar asked Sep 24 '17 10:09

Run


People also ask

What is mounted () in Vue?

The `mounted()` Hook in Vue The mounted() hook is the most commonly used lifecycle hook in Vue. Vue calls the mounted() hook when your component is added to the DOM. It is most often used to send an HTTP request to fetch data that the component will then render.

What is difference between created and mounted Vue JS?

As such, any DOM manipulation, or even getting the DOM structure using methods like querySelector will not be available in created() . As mentioned in the article on lifecycle hooks, created() is great for calling APIs, while mounted() is great for doing anything after the DOM elements have completely loaded.

Is Nuxt faster than Vue?

Nuxt. js stacks up to be the fastest eCommerce web framework. Nuxt. js is an open-source, serverless framework based on Vue.


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.

like image 144
Quoc-Anh Nguyen Avatar answered Oct 22 '22 02:10

Quoc-Anh Nguyen