Sometimes, we want to trigger events on an element with Vue.js.
In this article, we’ll look at how to trigger events on an element with Vue.js.
Trigger Events on an Element Using Vue.js
We can trigger events on an element with Vue.js by assigning a ref to the element we want to trigger events for.
Then we can call methods on the element assigned to the ref to trigger the event.
For instance, we can write:
<template>
<div id="app">
<button type="button" @click="myClickEvent">Click Me!</button>
<button type="button" @click="myClickEvent2" ref="myBtn">
Click Me 2!
</button>
</div>
</template>
<script>
export default {
name: "App",
methods: {
myClickEvent($event) {
const elem = this.$refs.myBtn;
elem.click();
},
myClickEvent2() {
console.log("clicked");
},
},
};
</script>
We have 2 buttons. And we want to trigger the click event on the 2nd button.
To do that, we add the myClickEvent
method which gets the button that’s assigned to the myBtn
ref.
And then we call click
on it.
In the 2nd button, we set the @click
directive to myClickEvent2
to log the click.
Now when we click on the first button, we see 'clicked'
logged.
Conclusion
We can trigger events on an element with Vue.js by assigning a ref to the element we want to trigger events for.