vue

Vue Created Vs Mounted lifecycle Hook


In this article, you will learn when to make use of the Created vs Mounted vue life cycle.

Created: During the created life cycle hook, the data instance is done with processing the options available. However, you do not have access to the DOM at this point.

<script>
export default {
  data() {
    return {
      message: "Shows a demo message",
    }
  },

  created() {
    this.displayMessage();
  },

  methods: {
    displayMessage() {
      console.log(this.message);
    },
  },
};
</script>

Mounted: During the mounted life cycle hook, the DOM has been mounted and we can perform DOM manipulations as getting the innerHTML.

Let’s say we have a method that changes the content of an element.

<template>
  <div>
    <p id="message">Displaying a basic message</p>
  </div>
</template>

<script>
export default {
  methods: {
    changeMessage() {
      document.getElementById("message").innerHTML = "Displaying Changed Message";
    },
  },
};
</script>

It would be most appropriate to call this method using the mounted lifecycle hook for reasons we have earlier established.

<template>
  <div>
    <p id="message">Displaying a basic message</p>
  </div>
</template>

<script>
export default {
  mounted() {
    this.changeMessage();
  },

  methods: {
    changeMessage() {
      document.getElementById("message").innerHTML =
        "Displaying Changed Message";
    },
  },
};
</script>

Share on social media

//