Is it possible to trigger events using Vue.js? Is it possible to trigger events using Vue.js? vue.js vue.js

Is it possible to trigger events using Vue.js?


You need to get a reference to your button by using v-el like so:

<button type="button" @click="myClickEvent" v-el:my-btn>Click Me!</button>

Then, in your method:

function anotherRandomFunction() {    var elem = this.$els.myBtn    elem.click()}

It's just a native DOM click event. See v-el Documentation

Or since Vue 2.x:

<template>    <button type="button" @click="myClickEvent" ref="myBtn">        Click Me!    </button></template><script>export default {    methods: {        myClickEvent($event) {            const elem = this.$refs.myBtn            elem.click()        }    }}</script>

Since Vue uses and listens for native DOM events only. You can trigger native DOM events using the Element#dispatchEvent like so:

var elem = this.$els.myBtn; // Element to fire onvar prevented = elem.dispatchEvent(new Event("change")); // Fire eventif (prevented) {} // A handler used event.preventDefault();

This is not exactly ideal or best practice. Ideally, you should have a function that handles the internals and an event handler that calls that function. That way, you can call the internals whenever you need to.


If someone stumbles upon this, this is how I did it:

When using this.$refs.myBtn.click()

I get

“Uncaught TypeError: this.$refs.myBtn.click is not a function”

Changed it to: this.$refs.myBtn.$el.click()

To be clear: “$el” needs to be added for it to work.


Vue is by its nature narrowly focused – it is intended that other packages like jQuery (EDIT: for jQuery features other than DOM manipulation) to be used with it. I think using jQuery's trigger is just fine.

However, if you want to create your own events without jQuery, check out dispatchEvent:

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent

Or, for the particular case of click, there is a method on DOM elements you can use:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click