[Vue] 한 페이지에 동일한 checkbox 컴포넌트 다루기 (v-model)

쿼카쿼카·2023년 6월 7일
0

Vue / Nuxt

목록 보기
16/35

코드

// 부모 페이지
<template>
  <div>
    <label
      for="username"
      >성별</label
      >
    <CheckBoxComp
      :data="gender"
      @update-select="changeGenderSelect"
      ></CheckBoxComp>
  </div>
  <div>
    <label
      for="username"
      >재직상태</label
      >
    <CheckBoxComp
      :data="status"
      @update-select="changeStatusSelect"
      ></CheckBoxComp>
  </div>
</template>
<script setup lang="ts">
const gender = ref([
  { id: "male", title: "남자" },
  { id: "female", title: "여자" },
  { id: "none", title: "모름" },
]);

const status = ref([
  { id: "comp", title: "회사" },
  { id: "housePolice", title: "개꿀 백수" },
  { id: "CEO", title: "CEO" },
  { id: "student", title: "학생" },
]);

const selectedGender = ref<string[]>([]);
const selectedStatus = ref<string[]>([]);

function changeStatusSelect(arr: string[]) {
  selectedStatus.value = [...arr];
}

function changeGenderSelect(arr: string[]) {
  selectedGender.value = [...arr];
}

watch(
  () => selectedGender.value,
  () => console.log(selectedGender.value)
);
watch(
  () => selectedStatus.value,
  () => console.log(selectedStatus.value)
);
</script>
// 체크박스 컴포넌트
<template>
  <div>
    <div
      v-for="(item, index) in checkList"
      :key="index"
    >
      <input
        :id="item.id + index"
        v-model="select"
        name="checkList"
        type="checkbox"
        :value="item.title"
      />
      <label
        :for="item.id + index"
        >{{ item.title }}</label
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { PropType } from "nuxt/dist/app/compat/capi";

interface Props {
  id: string;
  title: string;
}

const props = defineProps({
  data: {
    type: Array as PropType<Props[]>,
    default: [] as Props[],
  },
});

const checkList = ref(props.data);
const select = ref([]);

const emit = defineEmits<{
  (e: "update-select", arr: string[]): void;
}>();

watch(
  () => select.value.length,
  () => emit("update-select", select.value)
);
</script>

input의 id를 다르게 해준다.

  • 한 페이지 같은 컴포넌트 사용시 주의할 점은 각 input 등의 id를 다르게 해줘야한다.
  • 안 그러면 하나 체크했을 때 같은 컴포넌트를 사용하는 모든 것들이 체크되는 무서운 현상이...
  • props로 꼭 데이터를 넘겨줘 다른 값의 id를 할당한다.

체크리스트 체크 된 목록

  • input태그에 v-model로 select된 배열을 넣어준다.
  • 목록을 watch하여 변할 때마다 부모 컴포넌트에 넘겨준다.
profile
쿼카에요

0개의 댓글