Home > database >  How to know the iteration in v-for
How to know the iteration in v-for

Time:10-30

i'm in Vue.js I made a radio input component, I use a v-for to display all the input and label, I would like to know if I can tell it to pass the checked attribute to the element from the first iteration of the v-for loop

<div v-for="(option) in options" :key="option.name">
  <label class="form-check-label mr-2" :for="option.for">
    {{ option.name }}
  </label>
  <input
    v-model="selectedChoice" 
    class="mr-4" 
    type="radio" 
    name="radio" 
    :id="option.for" 
  />
</div>

Thanks for your help

CodePudding user response:

if I understand you correct you want to check your first radio button from your v-for.

You have two options to achieve that:

First option
You can set selectedChoice to your first choice like this:

data() {
  return {
    options: ['yourChoice1', 'yourChoice2'] //you have to set your array in here
    selectedChoice: 'yourChoice1',
  }
}

Second option
You set your data prop to the first item in your array - this is able because you're using v-model - you do it like this:

this.selectedChoice = this.yourChoice[0]

Hopefully this helps you out - please let me know!

  • Related