What Is the Difference Between the Created and Mounted in Vue?

What Is the Difference Between the Created and Mounted in Vue?

hackernoon.com hackernoon.com3 months ago in #Dev Love35

One of the issues that most of the people get perplexed about when speaking about lifecycle hooks in Vue, is the distinction between created and fastened. They each have identical names, and they really feel like they will have to do the identical factor, however there are some delicate variations. The Difference between created and fastened in Vue To start with, each created() and fastened() have get admission to to the knowledge and props to your prototype. For instance, each hooks will console log ‘My Message’ under, in addition to the default worth for myProp, which is ‘Some Prop’: export default { knowledge() { go back { msg: ‘My Message’ } }, props: { myProp: { sort: String, default: ‘Some Prop’ } }, created() { console.log(this.msg); console.log(this.myProp); }, fastened() { console.log(this.msg); console.log(this.myProp); } } Prop Inheritance for created and fastened The elementary distinction between created() and fastened() is you should not have get admission to to the DOM in created() but. Even when you set a assets, it’s going to nonetheless be to be had each in created() and fastened() In the above instance, if we attempt to reference this.$el, it’s going to go back null in created(), and it’s going to go back the DOM component in fastened(): export default { created() { // Returns null console.log(this.$el); }, fastened() { // Returns the DOM component in console: console.log(this.$el); } } As such, any DOM manipulation, and even getting the DOM construction the usage of strategies like querySelector may not be to be had in created(). created() is excellent for calling APIs, whilst fastened() is excellent for doing the rest after the DOM parts had been totally loaded. Composition API and created or fastened One caveat to that is that in case you are the usage of the Composition API, created(), and certainly earlier thanCreated() now not exists. You need to as an alternative use setup(). This serve as takes the position of each created() and earlier thanCreated(). Therefore, the DOM remains to be now not to be had in setup(). In the Composition API, fastened() stays unchanged. Also Published Here Love  » Read More

Like to keep reading?

This article first appeared on hackernoon.com. If you'd like to keep reading, follow the white rabbit.

View Full Article

Leave a Reply