Categories
JavaScript Answers Vue

How to run a component method on load with Vue.js?

Spread the love

Sometimes, we want to run a component method on load with Vue.js.

In this article, we’ll look at how to run a component method on load with Vue.js.

How to run a component method on load with Vue.js?

To run a component method on load with Vue.js, we can call them in the created hook.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<div id='app'>

</div>

to add the Vue script and app container.

Then we write:

const v = new Vue({
  el: '#app',
  template: `<p>hello</p>`,
  data: {
    content: 'hello world'
  },
  methods: {
    hello() {
      console.log('hello');
    },
  },
  created() {
    this.hello()
  }
})

to define the hello method in the methods object property.

Then we call this.hello in the created hook.

Therefore, we see 'hello' logged when the component loads.

Conclusion

To run a component method on load with Vue.js, we can call them in the created 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 *