0
0
Vueframework~5 mins

v-model with radio buttons in Vue

Choose your learning style9 modes available
Introduction

v-model with radio buttons lets you easily link a group of radio buttons to a single value. This way, when you pick one option, Vue automatically updates the value for you.

You want users to select one option from a small list, like choosing a color or size.
You need to bind a form input to your data so it updates automatically when the user picks a radio button.
You want to keep your code simple by avoiding manual event handling for radio buttons.
Syntax
Vue
<input type="radio" v-model="selectedValue" value="option1" />
<input type="radio" v-model="selectedValue" value="option2" />

The v-model directive binds the radio buttons to the same data property.

The value attribute on each radio button sets what value selectedValue will have when that button is chosen.

Examples
This example sets up two radio buttons bound to picked. Initially, 'A' is selected.
Vue
<template>
  <input type="radio" v-model="picked" value="A" /> A
  <input type="radio" v-model="picked" value="B" /> B
</template>

<script setup>
import { ref } from 'vue'
const picked = ref('A')
</script>
Here, radio buttons are wrapped in labels for better accessibility. The selected choice is shown below.
Vue
<template>
  <label>
    <input type="radio" v-model="choice" value="yes" /> Yes
  </label>
  <label>
    <input type="radio" v-model="choice" value="no" /> No
  </label>
  <p>You picked: {{ choice }}</p>
</template>

<script setup>
import { ref } from 'vue'
const choice = ref('no')
</script>
Sample Program

This component shows three radio buttons for fruits. The selected fruit is stored in fruit and displayed below. Initially, Banana is selected.

Vue
<template>
  <h2>Pick your favorite fruit:</h2>
  <label>
    <input type="radio" v-model="fruit" value="Apple" /> Apple
  </label>
  <label>
    <input type="radio" v-model="fruit" value="Banana" /> Banana
  </label>
  <label>
    <input type="radio" v-model="fruit" value="Cherry" /> Cherry
  </label>
  <p>Your choice: {{ fruit }}</p>
</template>

<script setup>
import { ref } from 'vue'
const fruit = ref('Banana')
</script>
OutputSuccess
Important Notes

Wrap radio buttons in <label> tags to improve accessibility and make clicking the text select the button.

Make sure all radio buttons bound with v-model share the same data property to work as a group.

Summary

v-model binds radio buttons to a single data value.

The value attribute sets what value is assigned when a radio button is selected.

Use labels for better user experience and accessibility.