

.vue 확장자를 사용해 각 파일에 해당 컴포넌트를 정의한다.App.vue, 자식 컴포넌트 : ChildComponent.vue)<scripts> 안에서 components 옵션을 통해 등록해야 한다.<div>)와 구별하기 위해 PascaslCase 태그명을 사용하는게 좋다.<!-- App.vue -->
<template>
<h1>아래에 자식 컴포넌트가 있습니다.</h1>
<ChildComponent />
<ChildComponent />
<ChildComponent />
</template>
<script>
import ChildComponent from './components/ChildComponent.vue'
export default {
name: 'App',
components: {
ChildComponent
}
}
</script>
<!-- ChildComponent.vue -->
<template>
<p>{{ data }}</p>
</template>
<script>
export default {
data() {
return {
data: '자식 컴포넌트'
}
}
}
</script>
props를 통해 사용자가 컴포넌트에 속성을 정의할 수 있다.<script> 안에서 props를 정의하면 된다.BlogPost.vue에서 props로 title을 정의하고, App.vue의 <template>안에서 <BlogPost> 컴포넌트에 :title을 통해 데이터를 전달한다.<!-- App.vue -->
<template>
<h1>Blog</h1>
<ul>
<BlogPost v-for="post in posts" :key="post.index" :title="post.title" />
</ul>
</template>
<script>
import BlogPost from './components/BlogPost.vue'
export default {
components: {
BlogPost
},
data() {
return {
posts: [
{ title: 'Vue와 함께한 나의 여행' },
{ title: 'Vue로 블로깅하기' },
{ title: 'Vue가 재미있는 이유' }
]
}
}
}
</script>
<!-- BlogPost.vue -->
<template>
<li>{{ title }}</li>
</template>
<script>
export default {
props: ['title']
}
</script>
자식 컴포넌트에 이벤트를 등록하고 부모 컴포넌트에 데이터 속성을 추가하여 상위 항목과 다시 통신하는 기능을 사용해보려고 한다.
postFontSize 데이터 속성을 추가한다.data() {
return {
posts: [
/* ... */
],
postFontSize: 1
}
}
<ul> 엘리먼트에 :style 속성을 추가하여 fontSize를 정의한다.<ul :style="{ fontSize: `${postFontSize}em`}">
<BlogPost v-for="post in posts" :key="post.index" :title="post.title" @enlarge-text="postFontSize += 0.1"/>
</ul>
<template>에 버튼을 추가한다.<template>
<li>{{ title }}</li>
<button type="button">텍스트 확대</button>
</template>
v-on 또는 @를 사용하여 자식 컴포넌트 인스턴스의 모든 이벤트를 수신하도록 할 수 있다.<BlogPost
...
@enlarge-text="postFontSize += 0.1"
/>
$emit 메서드를 통해 이벤트명을 전달하여 자체적으로 이벤트를 생성할 수 있다.<script> 안에 emits 속성을 통해 이벤트를 선언할 수 있다.<template>
<li>{{ title }}</li>
<button type="button" @click="$emit('enlarge-text')">텍스트 확대</button>
</template>
<script>
export default {
props: ['title'],
emits: ['enlarge-text']
}
</script>