How to get the value of button when clicked using vue.js

You can give your button a reference that Vue can access by giving it a tag ref="yourRef". Then you can access the value inside of your called function with this.$refs.yourRef.value.

Works for other Input elements as well ;)


You can simply give it as an argument to the function.

<button v-on:click="webcamSendRequestButton(0)"  type="button" class="webcam-send-request-button" :disabled="disabled">Verify</button>

JS

...
methods: {
  webcamSendRequestButton(value){
     //"value" is the clicked button value
  }
}
...

A better answer than the previous ones I believe is to inject the original DOM '$event' variable into your handler call:

v-on:click="webcamSendRequestButton($event)"

And receive it in your handler:

methods: {
  webcamSendRequestButton: function(e) {
    const buttonValue = e.target.value;
    .
    .
    .
  }
}

This is better for two well-connected reasons.

First, the code now has the same reasoning behind the initial intention: When a button is clicked, the handler should be able to read the value of the button that initiated the event. Other solutions that pass the value statically to the handler only mimic this, thus being more or less a hack.

Second, because the code now exactly matches the initial intention, the code becomes more maintainable. For example, if the value of each button gets to change dynamically by being bound to a variable value instead of a static value, the handler needs not to be changed at all. If the buttons grow or shrink in number, there is no need to change the handler code or define extra references or change the syntax of the handler call.

Tags:

Vue.Js