The difference between created and mounted in Vue

In a earlier article, I coated all of the different lifecycle hooks in Vue. One of many issues that most individuals get confused on when speaking about lifecycle hooks, is the distinction between created and mounted. They each have comparable names, and so they really feel like they need to do the identical factor, however there are some delicate variations.



The Distinction between created and mounted in Vue

To start with, each created() and mounted() have entry to the information and props in 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 {
    information() {
        return {
            msg: 'My Message'
        }
    },
    props: {
        myProp: {
            kind: String,
            default: 'My Prop'
        }
    },
    created() {
        console.log(this.msg);
        console.log(this.myProp);
    },
    mounted() {
        console.log(this.msg);        
        console.log(this.myProp);
    }
}
Enter fullscreen mode

Exit fullscreen mode



Prop Inheritance for created and mounted]

Be aware: even for those who set a property, it can nonetheless be accessible each in created() and mounted()

The elemental distinction between created() and mounted() is you should not have entry to the DOM in created() but. In our instance, if we attempt to reference this.$el, it can return null in created(), and it’ll return the DOM aspect in mounted():

export default {
    created() {
        // Returns null
        console.log(this.$el);
    },
    mounted() {
        // Returns the DOM aspect in console:
        console.log(this.$el);     
    }
}
Enter fullscreen mode

Exit fullscreen mode

As such, any DOM manipulation, and even getting the DOM construction utilizing strategies like querySelector won’t be accessible in created(). As talked about within the article on lifecycle hooks, created() is nice for calling APIs, whereas mounted() is nice for doing something after the DOM components have utterly loaded.



Composition API and created or mounted

The one caveat to that is that if you’re utilizing the Composition API, created(), and certainly beforeCreated() now not exists. It’s a must to as a substitute use setup(). This operate takes the place of each created() and beforeCreated(). Subsequently, the DOM continues to be not accessible in setup(). Within the Composition API, mounted() stays unchanged.

Add a Comment

Your email address will not be published. Required fields are marked *