I have just started using Vue.js and find myself continuously turning to jQuery to help in certain situations. Most recently I have attempted to, unsuccessfully "trigger" (or emulate) an event, such as an on click or blur event.
I know in jQuery you can do the following:
$('#my-selector').trigger('click');
But how can this be acheived using Vue.js? I am wanting to move away from using jQuery as much as possible.
Take the below as an example:
<div id="my-scope">
<button type="button" v-on="click: myClickEvent">Click Me!</button>
</div>
<script>
new Vue({
el: "#my-scope",
data: {
foo: "Hello World"
},
methods: {
myClickEvent: function(e) {
console.log(e.targetVM);
alert(this.foo);
},
anotherRandomFunciton: function() {
this.myClickEvent();
}
}
});
</script>
If I was to call anotherRandomFunciton, I would like it to emulate (or trigger) the above click event. However, I attempt this the event (or e in the above example) never gets passed to the function.
Does Vue.js have a method for achieving this?
Vue is by its nature narrowly focused – it is intended that other packages like jQuery 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
You need to get a reference to your button by using
v-el
like so:Then, in your method:
It's just a native DOM click event. See
v-el
DocumentationOr since Vue 2.x:
Since Vue uses and listens for native DOM events only. You can trigger native DOM events using the
Element#dispatchEvent
like so: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
Changed it to:
this.$refs.myBtn.$el.click()
To be clear: “
$el
” needs to be added for it to work.