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?
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.
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.
Nuxt. js stacks up to be the fastest eCommerce web framework. Nuxt. js is an open-source, serverless framework based on Vue.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With