In this tutorial, you’ll learn how to trigger events in Vue.js using the $refs.
We’ll be using the same approach as the one I’ve used in calling child functions using refs. If you’re familiar with refs you know that we can assign them to the DOM elements and then access those elements.
Let’s start by creating an HTML button and adding a ref attribute to it.
<div id="app">
<button type="button" ref="submitBtn" @click="submit">Submit</button>
</div>
We can now access this button directly using the $refs.
new Vue({
el: "#app",
methods: {
submit() {
console.log('submit')
}
},
mounted() {
this.$refs.submitBtn.click();
}
})
If we load this component, in the mounted() hook our button will be manually clicked. If everything works as expected you should see a ‘submit’ log in the console.
If you find this post useful, please let me know in the comments below and subscribe to my newsletter.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/vue-js-manually-trigger-events
PS: Make sure you check other Vue.js tutorials, e.g. detect mobile device in Vue.js, how to add current date to input type date in Vue.js, how to deploy Vue.js app to Firebase hosting.
Incoming search terms:
This did not work for me but this did.
this.$refs.submitBtn.$el.click();