WEB

vue3에서 props update emit

이팔청춘 2023. 10. 6. 18:01

vue3에서 부모-자식간 변경된 값을 공유하기 위해 다음과 같이 작성한다.

 

부모 컴포넌트

-꼭 v-model을 명시할 것

<template>
  <div>
    <ChildComponent v-model:childValue="parentValue" />
    <p>부모 컴포넌트의 데이터: {{ parentValue }}</p>
  </div>
</template>

<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent,
  },
  setup() {
    const parentValue = ref('부모 데이터');
    
    return {
      parentValue,
    };
  },
};
</script>

 

자식컴포넌트

-emit에 update를 명시하여 등록할 것

-props를 참조하는 다른 데이터를 만들 것

-자식컴포넌트에서 값 변경 시 watch하여 emit할 것

<template>
  <div>
    <button @click="changeChildValue">자식 컴포넌트 데이터 변경</button>
  </div>
</template>

<script>
import { ref, watch } from 'vue';

export default defineComponent({
  name: 'ChildComponent',
  emits: ['update:childValue'],
  components: {},
  props: {
    childValue: { required: false },
  },
  setup(props, { emit }) {
    const childValue = ref(props.childValue);

    const changeChildValue = () => {
      childValue.value = '자식 데이터 변경됨';
    };

    // 자식 컴포넌트의 childValue가 변경될 때
    const buf_childValue = ref(props.childValue);
    watch(buf_childValue, newValue => {
      emit('update:childValue', newValue); // localValue이 변경될 때 부모 컴포넌트로 값을 emit 합니다.
    });

    return {
      childValue,
      buf_childValue,
      changeChildValue,
    };
  },
};
</script>