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.