Sometimes, we want to trigger events using Vue.js.
In this article, we’ll look at how to trigger events using Vue.js.
How to trigger events using Vue.js?
To trigger events using Vue.js, we can assign a ref to the element we want to trigger the element from.
And then we can use the element’s methods to trigger the event.
For instance, we write
<template>
<div>
<button type="button" @click="myClickEvent" ref="myBtn">Click Me!</button>
</div>
</template>
<script>
//...
export default {
//...
methods: {
myClickEvent($event) {
const elem = this.$refs.myBtn;
elem.click();
},
},
//...
};
</script>
to assign the myBtn
ref to the button.
We set @click
to the myClickEvent
method to call it when we click on the button.
Then in the myClickEvent
method, we get the button element with this.$refs.myBtn
and assign it to elem
.
Finally, we call elem.click
to trigger the click event on the button.
Conclusion
To trigger events using Vue.js, we can assign a ref to the element we want to trigger the element from.
And then we can use the element’s methods to trigger the event.