본문 바로가기
javascript/Vue

Vue3 Component 예제를 통해 배워보기 (부모 자식간 연동하기)

by 산코디 2023. 1. 30.
vue3 component 대표 이미지




안녕하세요.
오늘은 Vue3 환경에서 Component을 다루는 방법을 포스팅하려고 합니다. 요즘은 Vue로 개발하는 환경이 정말 많아진 것 같은데요. Vue의 업데이트도 꾸준히 되면서 새로운 것이 많이 나오고 있습니다. 하지만 어떤 기술이든 기초적인 것이 가장 중요하기 때문에 오늘은 Vue의 Component에 대해서 알아보고 기초적인 것들이 익숙해지고 나면 조금씩 단계를 올려 포스팅해 보도록 하겠습니다. :) ( 저도 기초가 부족해서 오래 걸릴것 같긴 합니다..ㅜ )

Vue를 사용하다 보면 기능별, 메뉴별 등 시스템 설계에 따라 Component를 나눠서 개발을 많이 하는데, 현재 저도 프로젝트를 진행하면서 하나의 페이지를 개발할 때 Component 구조를 잡는데 시간이 많이 들어가고 있습니다 ㅎㅎ
그래서! 오늘은 그 기초적인 부분에 대해 Component 끼리 어떤 식으로 연동이 되는지 알아보도록 하겠습니다.


우선 간단하게 하나의 Component를 만들어 보겠습니다.


1. 기본 Component 만들기

<script>
export default {
    setup() {
        return {
        }
    }
}
</script>
<template>
    <div>Default Component</div>
</template>

간단하게 Component를 작성해 봤습니다. 기본적으로 <template> 태그를 선언하여 태그 안에 작성할 html 소스 코드를 넣어줍니다.
그리고 <template> 영역과 연동해 줄 <script> 영역을 작성해 주고 데이터를 연동할 기본적인 세팅만 하였습니다.


실행 결과
Vue_component_기본 예제 화면


vue-router를 연동하여 작성한 Component를 띄웠습니다. ( vue-router 예제 - https://sancode.tistory.com/36 )
위처럼 기본적인 Component는 작성 및 화면에 띄우는 것이 간단합니다.

다음은 현재 Component에서 자식 Component를 가져와서 import 시켜주는 예제를 한번 보겠습니다.


2. 부모 Component에서 자식 Component import 시키기

- 부모 Component : ParentComponent.vue
- 자식 1 Component : Child01Component.vue
- 자식 2 Component : Child02Component.vue

Component는 위와 같이 3개의 vue 파일로 구성을 하였습니다.

부모 Component ( ParentComponent.vue )
<script>
import Child01Component from './Child01Component.vue'
import Child02Component from './Child02Component.vue'
import { reactive } from 'vue'

export default {
    component: {
        Child01Component,
        Child02Component,
    },
    
    setup() {
        return {
        }
    }
}
</script>
<template>
    <div>
        <span>Parent Component</span>
        
        <!-- child 1번 컴포넌트 -->
        <Child01Component/>
            
        <!-- child 2번 컴포넌트 -->
        <Child02Component/>
    </div>
</template>

부모 Component에서 2개의 자식 Component를 추가해 줬습니다.

  1. 자식 Component import 시키기
  2. 위에서 import 시킨 자식 Component들을 자바스크립트에서 component: {} 요소에 추가
  3. <template> 영역에 추가하고 싶은 위치에 tag로 component 추가


자식 1번 Component ( Child01Component.vue )
<script>
export default {
    setup() {
    }
}
</script>
<template>
    <div>Child 01</div>
</template>
자식 2번 Component ( Child02Component.vue )
<script>
export default {
    setup() {
    }
}
</script>
<template>
    <div>Child 02</div>
</template>

2개의 자식 Component들은 기본 Component 작성하는 것과 동일하게 작성하였습니다.


실행 결과

vue3 부모자식 component 연동

실행 결과는 부모 Component에서 자식 Component 연동을 잘 시킨 것 같습니다!

반응형

위의 예제를 통해 진행했던 방식은 Vue3의 Composition API 방식으로 setup() 함수를 사용하는 방식입니다.
저는 추가로 조금 더 간결하고 가독성 좋은 <script setup> 방식으로 처리를 한번 해봤습니다.
위의 Component 중에서 부모 Component만 변경을 하였습니다.

부모 Component에서 <script setup> 변경
<script setup>
import Child01Component from './Child01Component.vue'
import Child02Component from './Child02Component.vue'
</script>
<template>
    <div>
        <span>Parent Component</span>

        <div>
            <!-- child 1번 컴포넌트 -->
            <Child01Component/>
            <!-- :parentType="parentType" -->
            <!-- child 2번 컴포넌트 -->
            <Child02Component />
        </div>
    </div>
</template>

아까 위에서 작성했던 방식과 비교를 하면 훨씬 간결하고 가독성도 좋습니다!
두 방식 모두 사용하는데 크게 지장은 없습니다. 다만 <script setup> 방식은 vue 공식 사이트에서 추천을 하는 방식이라 개인적으로 최근에 많이 사용하고 있는 방식입니다 :)


마무리

이렇게 간단하게 Component를 만드는 방법과 부모 자식 간 연동하는 방법을 알아봤습니다. router 처리하는 방법을 제외하곤 Component를 만드는 방법은 정말 간단합니다. 오늘 배운 것처럼 부모 자식 간의 Component 연동하는 게 익숙해지고 난 후에는 Vue 프로젝트의 구조를 잡을 때 한결 수월하게 진행될 수 있을 겁니다. :)

다음에는 오늘 배운 부모 자식 간의 Component에서 데이터를 연동하는 방법을 포스팅해 보도록 하겠습니다.


그럼 오늘도 저의 작고 소중한 글을 읽어주셔서 감사합니다.



* vue-router 예제
https://sancode.tistory.com/36

[Vue3] vue-router 사용하기 (예제)

안녕하세요. 오늘은 vue 개발을 하다 보면 페이지 라우트 처리에 꼭 필요한 router 처리하는 방법에 대해 포스팅하려고 합니다. 그럼 바로 시작하겠습니다. * 개발 환경 정보 - 운영체제 : macOS - vue :

sancode.tistory.com

반응형