How to run code only after the component is fully loaded and initialized in Vue.js?

Sometimes, we want to run code only after the component is fully loaded and initialized in Vue.js.

In this article, we’ll look at how to run code only after the component is fully loaded and initialized in Vue.js.

How to run code only after the component is fully loaded and initialized in Vue.js?

To run code only after the component is fully loaded and initialized in Vue.js, we can put the code in the mounted hook.

For instance, we write

<script>
//...
export default {
  //...
  mounted() {
    window.addEventListener("load", () => {
      // ...
    });
  },
  //...
};
</script>

to call window.addEventListener in the mounted hook to listen to the load event.

And then in the callback, we can run anything we want when the component is rendered.

Conclusion

To run code only after the component is fully loaded and initialized in Vue.js, we can put the code in the mounted hook.