-
vue3에서 props update emitWEB 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>'WEB' 카테고리의 다른 글
IoT Ubuntu20.04 서버 설정 (0) 2024.02.02 mariaDB 타임존 UTC로 변경 (1) 2023.11.28 Quasar 외곽선 아이콘 사용하는 방법 (0) 2023.08.25 InfluxDB 1.8.10 정리 (0) 2023.07.18 InfluxDB 1.8.1 윈도우에서 node.js 사용 (0) 2023.07.17