Recent Posts
Recent Comments
«   2024/05   »
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 31
Tags
more
Today
Total
관리 메뉴

고리타분한 개발자

[Vue JS] Components Within Components 본문

Vue JS/Step By Step

[Vue JS] Components Within Components

sunlee334 2017. 12. 4. 19:54

이번에는 지난 포스트에 이어서 여러개의 컴포넌트를 사용하는 방법을 알아보도록 하겠습니다.

지난번에는 task라는 이름의 template를 출력하는 컴포넌트를 만들어 보았는데요, 이번시간에는 좀더 나아가 task-list라는 리스팅 컴포넌트를 만들어 보도록 하겠습니다.


<!-- index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title></title>

</head>

<body>
<div id="root">
<task-list></task-list>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<script src="main.js"></script>

</body>

</html>


// main.js
Vue.component('task-list', {
template: `

<div>
<task v-for="task in tasks"> {{task.task}} </task>
</div>
`,
data() {
return {
tasks: [{
task: 'Go to the store',
complete: true
},
{
task: 'Go to the email',
complete: false
},
{
task: 'Go to the farm',
complete: true
},
{
task: 'Go to work',
complete: false
},

]
}

}

});

Vue.component('task', {
template: `<li><slot></slot></li>`
})

new Vue({
el: '#root'
})


이번에서 사용할 task-list라는 컴포넌트는 task라는 컴포넌트를 포함하고 있는 컴포넌트 입니다. task-list 컴포넌트의 template부분을 보면 


<div>
<task v-for="task in tasks"> {{task.task}} </task>
</div>


이렇게 division영역에 만약 div태그를 포함하지 않는다면 "Multiple root nodes returned from render function. Render function should return a single root node."라는 error를 발생시키게 됩니다. 

그럼 코드로 돌아가서, task 컴포넌트는 data값들을 리스팅 해주는 컴포넌트 입니다.

task-list 컴포넌트는 task 컴포넌트에 tasks라는 데이터를 바인딩 시켜주게되죠. 그러므로 결론적으로 우리가 얻게되는 결과값은 아래와 같습니다.





Comments