[Vuejs]-Using vue, determine which radio input is selected by accessing $refs

0👍

X is your ID:

<ul>
    <li v-for="x in 5">
        <label :for="`radio${x}`">radio{{x}}</label>
        <input type="radio" name="radio" :id="`radio${x}`" @change="getRef(`radio${x}`)" :ref="`radio${x}`">
    </li>
</ul>

methods: {
getRef (ref) {
  console.log(this.$refs[ref])
}}

0👍

This is happening since all the generated options are having the same ref ids. You could come over this with the following code.

TEMPLATE

<li class="mc-option" v-for="(option, i) in options" :key="i">
            <input :ref="['mcOption',i].join('-')" type="radio" name="option" :id="'option-' + i" class="" @click="radioSelected(i)"> {{i+1}}
</li>

JS

methods: {
            radioSelected: function (i) {
                let mcOption = this.$refs[['mcOption', i].join('-')]
                console.log(mcOption)
            }
        }

Points to note are:

  • :ref
  • a variable ref id by using ['mcOption', i].join('-'). This actually can be anything you want (but should change for every v-for iteration).

Please let me know if it does NOT work for you.

Leave a comment