Home » vue » How to get active buttons ref attribute and assign it to a variable in vue.js

How to get active buttons ref attribute and assign it to a variable in vue.js

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a page with 4 buttons:

<button ref='butOne' @click="saveRef">One</button>
<button ref='butTwo' @click="saveRef">Two</button>
<button ref='butThree' @click="saveRef">Three</button>
<button ref='butFour' @click="saveRef">Four</button>

I want the saveRef() function to save the reference of the button pressed to a variable like reference. How would the function look like?

data: function(){
    return {
        reference:""
    }
},

methods:{
    saveRef(){
        // what should go here?
    }
}

Answers:

You could pass the name of referenced button as a parameter of saveRef method as follows :

<button ref='butOne' @click="saveRef('butOne')">One</button>

in the method code :

methods:{
    saveRef(btn){
         this.reference=this.$refs[btn] // reference the button element which name passed as parameter
    }
}