<template>
  <div>
    <!-- isShow 값을 변경할 수 있는 버튼 -->
    <button @click="toggleShow">Toggle Show</button>
    <!-- 모달이 표시될 때 보여줄 콘텐츠 -->
    <div v-if="isShow">Modal Content</div>
  </div>
</template>

<script setup>
import { computed } from 'vue';

// Props를 가져옵니다
const props = defineProps({
  showModal: {
    type: Boolean,
    required: true
  }
});

// Emits를 설정합니다
const emit = defineEmits(['update:showModal']);

// isShow를 computed로 정의합니다
const isShow = computed({
  get: () => props.showModal,
  set: (newValue) => {
    emit('update:showModal', newValue);
  }
});

// 버튼 클릭 시 isShow 값을 변경하는 함수
const toggleShow = () => {
  isShow.value = !isShow.value;
};
</script>

isShow의 값이 변경될 때마다 set 메서드가 호출되고, 변경된 값이 emit 메서드를 통해 update:showModal 이벤트로 방출됩니다. 이 과정을 통해 props.showModal의 값을 업데이트하고, 이는 다시 isShow의 get 메서드에 반영됩니다. 이 순환구조를 통해 양방향 데이터 바인딩을 구현할 수 있습니다. 전체적인 흐름을 다시 정리하면 다음과 같습니다:

  1. 사용자가 버튼을 클릭하여 toggleShow 함수가 호출됩니다.
  2. toggleShow 함수는 isShow.value의 값을 반전시킵니다 (true -> false 또는 false -> true).
  3. isShow.value의 값이 변경되면서 computed 속성의 set 메서드가 호출됩니다.
  4. set 메서드는 새로운 값을 받아 emit('update:showModal', newValue)를 호출합니다.
  5. emit 메서드는 update:showModal 이벤트를 방출하고, 부모 컴포넌트에서 showModal prop의 값이 업데이트됩니다.
  6. props.showModal의 값이 변경되면 isShow의 get 메서드가 호출되어 props.showModal의 최신 값을 반환합니다.

이 흐름을 통해 isShow와 props.showModal이 항상 동기화됩니다.