N
N
Niki4h2021-11-20 11:11:57
Vue.js
Niki4h, 2021-11-20 11:11:57

How to make a radio button component in Vue?

Hello. I saw an example of working with radio buttons in Vuetify:

<template>
  <v-container
    class="px-0"
    fluid
  >
    <v-radio-group v-model="radioGroup">
      <v-radio
        v-for="n in 3"
        :key="n"
        :label="`Radio ${n}`"
        :value="n"
      ></v-radio>
    </v-radio-group>
  </v-container>
</template>

<script>
  export default {
    data () {
      return {
        radioGroup: 1,
      }
    },
  }
</script>


That is, the component v-radio-groupsomehow tracks v-radiointernally and returns the selected option. Actually, the question arose how to make the same behavior, instead of several v-radiowith v-model for one variable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-11-20
@Niki4h

Vue 2 Options API
Компонент радиогруппы:
props: [ 'value' ],
provide() {
  return {
    radioGroup: this,
  };
},

Компонент радиокнопки:
props: [ 'value' ],
inject: [ 'radioGroup' ],

<input
  type="radio"
  :value="value"
  :checked="radioGroup.value === value"
  @change="radioGroup.$emit('input', value)"
>

https://jsfiddle.net/d7aow8fq/

Vue 3 composition API
Компонент радиогруппы:
props: [ 'modelValue' ],
emits: [ 'update:modelValue' ],
setup(props, { emit }) {
  provide('radioGroupValue', computed({
    get: () => props.modelValue,
    set: v => emit('update:modelValue', v),
  }));
},

Компонент радиокнопки:
props: [ 'value' ],
setup() {
  return {
    radioGroupValue: inject('radioGroupValue'),
  };
},

<input
  type="radio"
  :value="value"
  v-model="radioGroupValue"
>

https://jsfiddle.net/d7aow8fq/2/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question