Categories
Vue Answers

How to Call a Vue.js Method on Page Load?

Spread the love

Sometimes, we want to call a method in our Vue.js component when we load the page.

In this article, we’ll look at how to call a method in our Vue.js component when we load the page.

Call a Vue.js Method on Page Load

We can call a Vue.js method on page load by calling it in the beforeMount component hook.

For instance, we can write:

<template>
  <div id="app"></div>
</template>

<script>
export default {
  name: "App",
  methods: {
    getUnits() {
      //...
    },
  },
  beforeMount() {
    this.getUnits();
  },
};
</script>

to add the getUnits method into the methods property.

And we call this.getUnits in the beforeMount hook.

this.getUnits is the getUnits method in the methods object property.

We can also make a method run on page load by calling it in the created hook:

<template>
  <div id="app"></div>
</template>

<script>
export default {
  name: "App",
  methods: {
    getUnits() {
      //...
    },
  },
  created() {
    this.getUnits();
  },
};
</script>

And we can do the same in the mounted hook:

<template>
  <div id="app"></div>
</template>

<script>
export default {
  name: "App",
  methods: {
    getUnits() {
      //...
    },
  },
  mounted() {
    this.getUnits();
  },
};
</script>

Conclusion

We can call a Vue.js method on page load by calling it in the beforeMount component hook.

We can also make a method run on page load by calling it in the created hook.

And we can do the same in the mounted hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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