안녕하세요!
프뚜(프로그래머 뚜)입니다!
[개발 환경]
- OS: windows 10 64bit
- git: 2.37.1.windows.1
- nodejs: v16.16.0
- npm: 8.15.0
- yarn: 1.22.19
- @vue/cli(vue3): 5.0.8
vue에서는 props와 emit이 있습니다.
- 자식 컴포넌트에서 부모 데이터 값 사용하기 (props)
- 자식 컴포넌트에서 부모 function 사용하기 (emit, emits)
가 있습니다. (자세한 내용은 링크를 통해 확인할 수 있습니다.)
vue3에서는 <script setup>을 통해 간결하게 코드를 사용할 수 있습니다.
- setup 기능 사용하기 (composition api)
script setup에서는 props와 emit을 어떻게 사용해야하는 지 포스팅하겠습니다.
1. 기초 세팅
# App.vue > router-view: path name은 '/'
# Main.vue > 메인입니다.: path name은 'main'
<script setup>으로 초기화 되어있는 상태입니다.
2. props를 통해 자식에서 부모의 데이터 출력하기(부모에서 자식에게 데이터 넘기기)
# App.vue
<template>
<!-- 2022.08.15[프뚜]: user 데이터를 Main.vue에서 출력하기 -->
<router-view
:user="user"/>
</template>
<script setup>
import { ref } from 'vue';
// 2022.08.15[프뚜]: user 데이터 생성
const user = ref('프뚜');
</script>
3. props를 통해 자식에서 부모의 데이터 출력하기 (자식에서 부모 데이터 출력하기)
# Main.vue
<template>
<div>Main입니다.</div>
<!-- 2022.08.15[프뚜]: props 값에서 user 사용 -->
props.user > {{ props.user }} <br/>
<!-- 2022.08.15[프뚜]: user를 바로 사용할 수 있음 -->
user > {{ user }}
</template>
<script setup>
import { defineProps } from "vue";
// 2022.08.15[프뚜]: 부모에서 받아온(props) 데이터를 연결
const props = defineProps({
user: String
});
// 2022.08.15[프뚜]: props에 있는 user 데이터 출력
console.log(props.user);
</script>
props는 defineProps를 통해 받아온 데이터의 형식을 지정 후 사용할 수 있습니다.
4. emit을 통해 자식에서 부모 function 사용하기 (부모에서 자식에게 함수 넘기기)
# @userChange="userChange"
<template>
<!-- 2022.08.15[프뚜]: user 데이터를 Main.vue에서 출력하기 -->
<!-- 2022.08.15[프뚜]: userChange method를 Main.vue에서 사용하기 -->
<router-view
:user="user"
@userChange="userChange"/>
</template>
<script setup>
import { ref } from 'vue';
// 2022.08.15[프뚜]: user 데이터 생성
const user = ref('프뚜');
// 2022.08.15[프뚜]: user 데이터 변경 method
const userChange = () => {
user.value = '먹뚜';
};
</script>
5. emit을 통해 자식에서 부모 function 사용하기 (자식에서 부모 함수 사용하기)
# {{ emit('method') }}
# emit('method');
<template>
<div>Main입니다.</div>
<!-- 2022.08.15[프뚜]: props 값에서 user 사용 -->
props.user > {{ props.user }} <br/>
<!-- 2022.08.15[프뚜]: user를 바로 사용할 수 있음 -->
user > {{ user }}
<!-- 2022.08.15[프뚜]: 부모 함수 사용하기 -->
{{ emit('userChange') }}
</template>
<script setup>
import { defineProps, defineEmits } from "vue";
// 2022.08.15[프뚜]: 부모에서 받아온(props) 데이터를 연결
const props = defineProps({
user: String
});
const emit = defineEmits([
'userChange'
]);
// 2022.08.15[프뚜]: 부모 함수 사용하기
emit('userChange');
</script>
emit은 defineEmits를 통해 받아온 함수명을 연결 후 사용할 수 있습니다.
해당 프로젝트는 gitlab에 제공되고 있습니다. (포스팅 제목과 Git History는 1:1 매칭입니다.)
https://github.com/JeongSeongSoo/vue-tistory
GitHub - JeongSeongSoo/vue-tistory
Contribute to JeongSeongSoo/vue-tistory development by creating an account on GitHub.
github.com
궁금하신 부분 또는 문제가 생긴 부분에 대해서 댓글 남겨주시면 빠르고 정확한 답변드리겠습니다.
'프로그램 > VUE' 카테고리의 다른 글
[VUE] 컴포넌트에 여러 개 v-model 사용하기 (props 값 바꾸기) (2) | 2022.08.19 |
---|---|
[VUE] slot 사용하기 (scoped) (3) | 2022.08.18 |
[VUE] teleport 사용하기 (원하는 곳으로 코드 이동) (10) | 2022.08.15 |
[VUE] 메모리 누수 관리하기 (라이프사이클 훅) (7) | 2022.08.12 |
[VUE] dotenv 사용하기 (8) | 2022.08.11 |