vue

Using the Vue mounted lifecycle hook


Life cycle hooks are windows to the driving factors of our frameworks. They help us keep track of what happens to our components. Typically, this is when they are created, updated, destroyed or before either happens.

Vue Mounted lifecycle hook is a function called after the instance is mounted. It is however worthy of note that, mounted does not guarantee that all child components have also been mounted. To ensure that the entire view has been rendered, we can use vm.$nextTick inside of mounted .

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

  mounted() {
    this.$nextTick(function () {
      this.displayMessage();
    });
  },

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

Basically, the method displayMessage is called when the component is mounted. this.$nextTick ensures that all child components are as well loaded before calling the function.


Share on social media

//