Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 |
Tags
- dex모드
- Component
- vue
- html 엔티티
- es6
- 티스토리챌린지
- vitre
- 앱 빌드
- promise
- setup 함수
- reactivity
- asynchronus
- hoisting
- let
- mobile dev tools
- const
- drective
- watch
- 오블완
- async
- 템플릿 문법
- composition API
- synchronus
- tdz
- composition api
- watchEffect
- await
- ref
- computed
- eruda
Archives
- Today
- Total
uxtry
vue: 컴포넌트 기초 본문
vue에서 컴포넌트(component)는 재사용 가능한 UI요소를 정의하는 기본 단위 입니다. 컴포넌트를 사용하면 코드를 모듈화하고 유지보수를 쉽게 할 수 있습니다.
1. 컴포넌트 기본 구조
- template: 컴포넌트의 HTMl 구조를 정의합니다.
- script: 컴포넌트의 데이터, 로직, 상태등을 정의합니다.
- style: 컴포넌트의 스타일을 정의합니다.(선택 사항)
2. 단일 파일 컴포넌트 예제
<!--부모 컴포넌트(App.vue)-->
<template>
<div>
<h1>Vue 컴포넌트 기초</h1>
<ChildComponent title="Hello Vue!" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent, // 자식 컴포넌트 등록
},
};
</script>
<!-- 자식 컴포넌트(ChildComponent.vue) -->
<template>
<div>
<h2>{{ title }}</h2>
<p>이것은 자식 컴포넌트입니다.</p>
</div>
</template>
<script>
export default {
props: {
title: {
type: String, // `title`은 문자열 타입이어야 함
required: true, // 필수 속성
},
},
};
</script>
★ Vue SFC Playground 코드 실행 →
3. 코드 설명
1) App.vue(부모 컴포넌트):
- 메인 컴포넌트에서 ChildComponent를 사용합니다.
- title="Hello Vue!"로 ChildConponent에 데이터를 전달합니다.
2) ChildComponetnt.vue(자식컴포넌트)
- props를 사용해 부모 컴포넌트로부터 데이터를 받습니다.
- title속성을 출력합니다.
4. 주요 개념
1) 컴포넌트 등록
- 지역등록(local Resistration): 특정 컴포넌트에서만 사용.
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
};
- 전역등록(global Rsistration): 애플리케이션 전체에서 사용
import ChildComponent from './ChildComponent.vue';
app.component('ChildComponent', ChildComponent);
2) props(부모 -> 자식 데이터 전달)
- 부모가 자식에게 데이터를 전달할 때 사용.
- 타입과 필수 여부를 지정 가능.
props: {
title: {
type: String,
required: true,
},
}
3) 이벤트(자식->부모 데이터 전달)
- 자식 컴포넌트에서 $emit 으로 이벤트를 발생시켜 부모와 상호작용.
<!--자식 컴포넌트-->
<template>
<button @click="sendToParent">클릭</button>
</template>
<script>
export default{
methods: {
sendToParent(){
this.$emit('custom-event','자식에서 보낸 데이터');
},
},
};
</script>
<!--부모 컴포넌트-->
<ChildComponent @custom-event="handleEvent">
<script>
export default {
methods: {
handleEvent(data){
console.log('받은 데이터', data);
}
},
}
</script>
4) Slot(슬롯)
- 부모가 자식 컴포넌트의 특정 영역에 내용을 삽입.
<!-- 자식 컴포넌트 -->
<template>
<div>
<slot>기본 슬롯 콘텐츠</slot>
</div>
</template>
<!-- 부모 컴포넌트 -->
<ChildComponent>
<p>부모가 삽입한 콘텐츠</p>
</ChildComponent>
6. 컴포넌트 사용 시 이점
- 코드 재사용 증가.
- 유지보수 용이.
- 대규모 애플리케이션에서 구조화된 개발 기능.
이 기본 구조와 개념을 이해하면 Vue 컴포넌트를 활용해 더 복잡한 UI를 구현할 수 있습니다.
'Vue.js 3 주요 문법 (vue:)' 카테고리의 다른 글
| vue: Props (1) | 2024.12.19 |
|---|---|
| vue: Single File Component (0) | 2024.12.19 |
| vue: Watch와 WatchEffect (0) | 2024.11.26 |
| vue: 양방향 바인딩(v-model) (0) | 2024.11.22 |
| vue: 이벤트 처리 (0) | 2024.11.21 |