6
4

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 5 years have passed since last update.

【Nuxt.js】ラジオボタンのイベントの値を取得する方法

Posted at

やりたいこと

ダウンロードしたsvgを使って、ラジオボタンを実装したい
そのためにラジオボタンのイベントの値を取得したい(changeイベント)

実際のコード

radio.vue
<template>
  <section>
    <div class="radio_label">性別</div>
    <div class="radio_select">
      <input
        type="radio"
        name="sex"
        id="male"
        value="男性"
        v-model="picked"
        v-on:change="onChange"
      />
      <label for="male">
        <RadioInSvg v-if="maleFlag" />  <!-- maleFlagがtrueの場合 -->
        <RadioOutSvg v-else />  <!-- maleFlagがfalseの場合 -->
        男性
      </label>
      <br />
      <input
        type="radio"
        name="sex"
        id="female"
        value="女性"
        v-model="picked"
        v-on:change="onChange"
      />
      <label for="female">
        <RadioInSvg v-if="femaleFlag" />  <!-- femaleFlagがtrueの場合 -->
        <RadioOutSvg v-else />  <!-- femaleFlagがfalseの場合 -->
        女性
      </label>
    </div>
  </section>
</template>

<script>
import RadioInSvg from "@/assets/radio_in.svg"  // svgはassets配下に配置しimportする
import RadioOutSvg from "@/assets/radio_out.svg"

export default {
  components: {
    RadioOutSvg,
    RadioInSvg
  },
  data() {
    return {
      maleFlag: false,  // 初期値の設定
      femaleFlag: false  // 初期値の設定
    }
  },
  methods: {
    onChange(event) {  // クリックイベントでイベント発火
      if (event.target.value === "男性") {  // input type="radio"のvalueを取得して判定
        this.maleFlag = true
        this.femaleFlag = false
      } else if (event.target.value === "女性") {
        this.maleFlag = false
        this.femaleFlag = true
      }
    }
  }
}
</script>
  • 今回svgを使用してラジオボタンの実装を行うので、ラジオボタンの標準スタイルは非表示に変更
<style>
input[type="radio"] {
  display: none;
}
</style>

参照

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?