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

Written by smpnjn | Published 2022/05/15
Tech Story Tags: vuejs | vue | javascript | web-development | created-and-mounted-in-vue | coding | learn-to-code | coding-skills

TLDRBoth created() and mounted() have access to the data and props on your prototype. created() is great for calling APIs, while mounted() is great for doing anything after the DOM elements have been completely loaded. via the TL;DR App

One of the things that most people get confused about when talking about lifecycle hooks in Vue, is the difference between created and mounted. They both have similar names, and they feel like they should do the same thing, but there are some subtle differences.

The Difference between created and mounted in Vue

To begin with, both created() and mounted() have access to the data and props on your prototype.

For example, both hooks will console log 'My Message' below, as well as the default value for myProp, which is 'Some Prop':

export default {
    data() {
        return {
	        msg: 'My Message'
        }
    },
    props: {
        myProp: {
            type: String,
            default: 'Some Prop'
        }
    },
    created() {
        console.log(this.msg);
        console.log(this.myProp);
    },
    mounted() {
        console.log(this.msg);        
        console.log(this.myProp);
    }
}

Prop Inheritance for created and mounted

The fundamental difference between created() and mounted() is you do not have access to the DOM in created() yet.

Even if you set a property, it will still be available both in created() and mounted()

In the above example, if we try to reference this.$el, it will return null in created(), and it will return the DOM element in mounted():

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

As such, any DOM manipulation, or even getting the DOM structure using methods like querySelector will not be available in created().

created() is great for calling APIs, while mounted() is great for doing anything after the DOM elements have been completely loaded.

Composition API and created or mounted

One caveat to this is that if you are using the Composition API, created(), and indeed beforeCreated() no longer exists. You have to instead use setup(). This function takes the place of both created() and beforeCreated().

Therefore, the DOM is still not available in setup(). In the Composition API, mounted() remains unchanged.


Also Published Here


Written by smpnjn | Product, Engineering, Web
Published by HackerNoon on 2022/05/15