Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a click handler to a ref?

Tags:

vue.js

vuejs2

I'm using a 3rd party package but need to add a small piece of interaction.

The package has a button with ref of "next". Is there anyway to add a click handler to this ref?

like image 359
panthro Avatar asked Dec 17 '22 23:12

panthro


2 Answers

This may help:

public mounted() {
    const next = this.$refs.next as HTMLElement;
    next.addEventListener('click', this.onNextClick, false);
}

public onNextClick() {
    // do your stuff here
}
like image 95
Krantisinh Avatar answered Jan 06 '23 22:01

Krantisinh


I've ran into this question seeking a solution for a similar problem. However my case was that a ref attribute was set on a Vue Component object. Using simple addEventListener on a referenced object I got an error:

addEventListener is not a function

The solution is to call the function on referenced component's $el property, being an actual HTML element.

this.$refs.next.$el.addEventListener('click', function() {
  /* do stuff here*/
}, false);

From the comment's in the previous answers I see that it might also be the case for OP.

like image 23
Jakub Licznerski Avatar answered Jan 06 '23 23:01

Jakub Licznerski