Search code examples
javascriptjqueryvue.jsreferenceref

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


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?
    }
}


Solution

  • 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
        }
    }