기본 콘텐츠로 건너뛰기

[vuejs 관련] Radio component

Radio component


component .vue파일

<template>
  <div class="m_radio">
    <input type="radio" :name="name" :id="idfor" :value="value" :checked="value === selected">
    <label :for="idfor">{{ txt }}</label>
  </div>
</template>

<script setup>
const props = defineProps({
  name: {
    type: String,
    defatult: undefined
  },
  idfor: {
    type: String,
    defatult: undefined
  },
  value: {
    type: String,
    defatult: undefined
  },
  txt: {
    type: String,
    default: ''
  },
  selected: {
    type: String,
    defatult: undefined
  }
})
</script>

<style scoped src="./Radio.scss"></style>
<!--
  // 부모 컴포넌트에서 사용 시
  # name : radio name
  # idfor : radio id = label for
  # value : radio value
  # selected : 현재 선택된 radio
  # txt : label

  <Radio name="name" idfor="idfor" value="value" txt="text" />

  ex : <Radio name="useyn" idfor="usey" :selected="info.radiochk" @change="check($event)" txt="사용" />

  const check = (e) => {
    info.value.radiochk = e.target.value;
    console.log(info.value.radiochk, e.target.id, e.target.parentElement.querySelector("label").innerText);
  }
 -->


불러오는 .vue 파일에

<template>
  ...
  <Radio name="useyn" idfor="usey" value="y" txt="사용" :selected="info.radiochk" @change="check($event)" />
  <Radio name="useyn" idfor="usen" value="n" txt="미사용" :selected="info.radiochk" @change="check($event)" />
  ...
</template>

<script setup>
import { ref } from "vue";
import Radio from "@/components/Radio.vue";

//
const info = ref({
  radiochk: "y",
})

//
const check = (e) => {
  info.value.radiochk = e.target.value;
  console.log(info.value.radiochk, e.target.id, e.target.parentElement.querySelector("label").innerText);
}

css

@import "@/assets/scss/mcolor.scss";

.m_radio {
  display: flex;
  label {
    padding-left: 2.2rem;
    padding-right: 0.5rem;
    position: relative;
    height: 2rem;
    line-height: 2rem;
    &::before,
    &::after {
      content: "";
      margin: auto;
      position: absolute;
      top: 0;
      bottom: 0;
    }
    &::before {
      left: 0;
      width: 1.4rem;
      height: 1.4rem;
      border: 1px solid $c_gray_9;
      border-radius: 50%;
    }
    &::after {
      left: 0.3rem;
      width: 1rem;
      height: 1rem;
      background-color: #fff;
      border-radius: 50%;
      transition: background-color 0.2s ease;
    }
  }
  input:checked + label::after {
    background-color: $c_gray_5;
  }
  ~ .m_radio {
    margin-left: 2rem;
  }
}

//== pc가 아닐 때
.nopc {
}

Radio component


끝.