[Metanet]/[실무] 문제해결

[Vue TreeSelect 컴포넌트에게 '기본 선택 값' 주는 방법] How to set default selected value into vue tree-select component

Ben의 프로그램 2024. 8. 24. 21:50
728x90


// ======================== ======================== ========================

실무 작업 중에 Vue TreeSelect 를 활용해서 작업을 하게 되었는데, 수정 페이지라서 TreeSelect 컴포넌트에서 기본적으로 유저가 이전에 선택한 항목들이 선택된 채로 렌더링이 되어야 하는 문제를 만나게 되었다. 

 

아쉽게도 TreeSelect 컴포넌트에서는 Disabled 와 같이, Selected 라는 인터페이스가 뚫려있지 않아서 문제 해결을 위해서 이리 저리 고민하다가, 아래와 같은 해결방법을 만나서 해결하였다. 

 ======================== ======================== =========================== //

 

해결방법
해결방법은 value 를 이용하는 것인데, value 의 초기 값은 무조건 null 로 세팅이 되어야 했다. 그래서 버튼을 하나 만들어서 그것을 렌더링이 끝나면 눌러주기 식으로 처리했는데, 포인트는 always open = true 로 설정해야만 정상 동작 한다. 왜냐하면, 내부적으로 v-if 를 활용하기 때문에 컴포넌트 자체가 생성되지 않아서 value 를 설정해주어봤자 에러만 뱉어낸다. 

<template>
  <div>
    <!-- Vue-Treeselect Component -->
    <treeselect
      v-model="selectedValue"
      :multiple="true"
      :options="options"
      @input="onSelect"
      :always-open="alwaysOpen"
    />
    
    <!-- Button to Programmatically Select an Option -->
    <button @click="selectOption('option1')" style="margin-top: 150px;" ref="selectRef">Select Option 1</button>
  </div>
</template>

<script>
// Import the vue-treeselect component and its CSS
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  mounted () {
    this.$refs.selectRef.click();
  },

  components: {
    Treeselect,
  },

  data() {
    return {
      selectedValue: null, // Initially no value is selected
      options: [
        { id: 'option1', label: 'Option 1' },
        { id: 'option2', label: 'Option 2' },
        // Add more options as needed
      ],
      alwaysOpen: true,
    };
  },
  methods: {
    selectOption(optionId) {
      // Set the selected value programmatically
      this.selectedValue = [optionId];

      // Optional: Emit an event to simulate a user interaction
      this.$emit('input', this.selectedValue);
    },
    onSelect(value) {
      console.log('Selected Value:', value);
    },
  },
};
</script>

<style>
/* Add any styles if needed */
</style>

그런데, 위와 같이 작업을 하면 다음과 같이 tree menu 가 항상 화면에 나타나게 된다. 
이런 경우, v-if 대신 DOM 에 element 를 항상 추가하고, css 를 이용해서 화면에 가리는 v-show 를 이용하면 화면에 초기 노출을 피해줄 수 있다. 

 

'[Metanet] > [실무] 문제해결' 카테고리의 다른 글

[ Vue3 강제렌더링 ]  (0) 2025.02.26