728x90

object 타입 선언은 문법이 조금 다르기에 메모해 본다 

vue3 에서는 ref 로 선언을 해야 하는 경우 아래와 같이 선언한다.

const selectedLangSrcOption = ref({
  // 자식 컴포넌트가 예상하는 프로퍼티와 값을 제공
  key: 'value',
});

초기화 해줄때 역시 key value 의 형태로 초기화를 해주어야 waring 메세지가 에러처럼 나지 않으니 참고 해야 한다. 

const selectedLangSrcOption = ref({ key : "" });

 

아래는 vue2 에서 object 타입의 객체를 선언 하는 예제 이다. 

셀렉트 컴포넌트에서 보통 이런 key value 의 형태를 많이 사용하기에 알아 두면 유용하게 사용 할수 있다. 

 

부모 컴포넌트 

<template>
  <div>
    <SelectComponent
      class="selectbox-gray"
      :options="langsTgtOpt"
      id="tgtlan"
      :selectValue="selectedLangTgtOption"
    />
    <button @click="resetSelectBox">Reset Select Box</button>
  </div>
</template>

<script>
import SelectComponent from "./SelectComponent"; // 자식 컴포넌트의 경로에 맞게 수정하세요

export default {
  data() {
    return {
      langsTgtOpt: [
        { key: "Option 1", value: "Value 1" },
        { key: "Option 2", value: "Value 2" },
        { key: "Option 3", value: "Value 3" },
      ],
      selectedLangTgtOption: {}, // 초기값은 빈 객체로 설정
    };
  },
  methods: {
    resetSelectBox() {
      this.selectedLangTgtOption = {}; // 버튼을 클릭하면 선택된 값 초기화
    },
  },
  components: {
    SelectComponent,
  },
};
</script>

자식 컴포넌트

<template>
  <select v-model="selectedValue">
    <option v-for="option in options" :key="option.key" :value="option">{{ option.value }}</option>
  </select>
</template>

<script>
export default {
  props: {
    options: {
      type: Array,
      required: true,
    },
    selectValue: {
      type: Object, // 셀렉트 박스에서 선택된 값을 객체로 받습니다.
      required: true,
    },
  },
  computed: {
    selectedValue: {
      get() {
        return this.selectValue;
      },
      set(newValue) {
        this.$emit("update:selectValue", newValue);
      },
    },
  },
};
</script>
728x90

+ Recent posts