1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ラジオボタンで選択解除をする(v-radio-group, v-radio)

Last updated at Posted at 2023-05-24

vuetifyのv-radio-group/v-radioを使ったラジオボタンの実装において、現在選択されているものをクリック/タップした場合に選択解除する

選択を解除するというとラジオボタンの意図から外れると思うのでフォーム設計を見直すのがベターですが、やる必要が出た時用メモ

バージョン

nuxt3, vuetify3

"nuxt": "^3.2.3"
"vuetify": "^3.1.7"

実装

sample.vue
<template>
  <v-radio-group v-model="hoge" @click="clearRadioSelected($event, 'hoge')">
    <v-radio label="はい" value="1"></v-radio>
    <v-radio label="いいえ" value="2"></v-radio>
  </v-radio-group>
  <v-radio-group v-model="fuga" @click="clearRadioSelected($event, 'fuga')">
    <v-radio label="YES" value="1"></v-radio>
    <v-radio label="NO" value="2"></v-radio>
  </v-radio-group>
</template>

<script setup lang="ts">
const hoge = ref();
const fuga = ref();
const clearRadioSelected = (event: Event, target: string) => {
  if (event.target instanceof HTMLInputElement && event.target.type === "radio" && event.target.tagName === "INPUT") {
    const value = event.target.value;
    switch (target) {
      case "hoge":
        hoge.value = value && value === hoge.value ? undefined : value;
        break;
      case "fuga":
        fuga.value = value && value === fuga.value ? undefined : value;
        break;
    }
  }
};
</script>
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?