Home > Net >  Using V-For to provide values to Radio Button input?
Using V-For to provide values to Radio Button input?

Time:02-16

Apologies if this is a super basic question, but I'm building a Radio Button component, which iterates over Array of Objects, each representing a User.

All the documentation and examples I see have hardcoded values, whereas my Array has constantly changing Users, what I want to know is, how I would adapt the below code to take the name of the Users as a value for each radio button.

<input type="radio" id="one" value="One" v-model="picked">
<br>
<input type="radio" id="two" value="Two" v-model="picked">
<br>
<input type="radio" id="two" value="Two" v-model="picked">
<br>
<span>Picked: {{ picked }}</span>
export default {
  name: 'UserRadioButton'
  data() {
    return {
      picked: 'name',
      Users: [{name:"Mary"},{name:"John"},{name:"Hank"}]
    };
  },
}

CodePudding user response:

  1. Render the list of Users with v-for.
  2. Bind the <input>.value to each item's name in the v-for. This sets the radio's intended value when selected, and that's reflected in the v-model.
<label v-for="user in Users" 1️⃣ >
  <input type="radio" v-model="picked" :value="user.name" 2️⃣ />
  <span>{{ user.name }}</span>
</label>

demo

  • Related