Loop 를 이용한 리스트 렌더링
state 와 props 에 따른 component 제어에 대해 학습합니다.
Loop
아래와 같이 비슷한 패턴의 component 가 반복될 때 어떻게 구성하는 것이 좋을까요?
Copy <Item>
<Item>
<Item>
<Item> x 100
위 처럼 모든 component 를 그려주는 방법도 있지만, loop 를 이용하면 손쉽게 반복되는 component 를 구성할 수 있습니다.
1. 프로젝트 구성
직접 실습해보며 loop 사용법을 알아보겠습니다.
(예제는 이전의 초기 구성되었던 환경에서 시작합니다.)
2. 데이터를 준비
component 를 구성하기 위해 webtoon 데이터를 준비합니다.
Copy // App.vue
export default {
data() {
return {
webtoons: [
{
name: "햄스터와 그녀",
link: "http://webtoon.daum.net/webtoon/view/hamsterandher",
img:
"http://t1.daumcdn.net/webtoon/op/478cdf37f585607982ffa9e35b432e8503be8a54"
},
{
name: "프롬 스타",
link: "http://webtoon.daum.net/webtoon/view/fromstar",
img:
"http://t1.daumcdn.net/webtoon/op/a7fb953d722c1130bfc18440f7e3ce448ece57a1"
},
{
name: "위대한 로맨스",
link: "http://webtoon.daum.net/webtoon/view/greatromance",
img:
"http://t1.daumcdn.net/webtoon/op/a816281cb4df5c50a20ac386fd6e496643d0f085"
},
{
name: "빛나는 손을",
link: "http://webtoon.daum.net/webtoon/view/Hand",
img: "http://t1.daumcdn.net/cartoon/5913FCAC0234C50001"
}
]
};
}
};
3. Component 준비
Webtoon.vue
component 를 만듭니다. Webtoon component 는 Webtoon 데이터를 props 로 받습니다.
Copy // Webtoon.vue
<template>
<div>
<h2>Webtoon</h2>
<ul class="wrap"></ul>
</div>
</template>
<script>
export default {
props: {
items: { type: Array, default: () => [] }
}
};
</script>
<style>
</style>
App.vue
에서 component 를 불러오고 props 를 전달해줍니다. App 의 state (webtoons) 를 webtoon 에게 props 로 데이터를 넘겨줍니다.
Copy // App.vue
<template>
<div id="app">
<Webtoon :items="webtoons"/>
</div>
</template>
<script>
import Webtoon from "./components/Webtoon";
export default {
components: {
Webtoon
}
// data .....
}
</script>
4. Loop 를 이용하여 component 구성하기
v-for
라는 디렉티브를 이용하여 리스트를 렌더링 할 수 있습니다.
Copy <div v-for="i in 10" :key={i}>{i}</div>
아래와 같이 리스트가 구성됩니다. 리스트 렌더링 되는 component 는 항상 key
라는 props 값이 필요합니다.
key
가 필요한 이유를 간단하게 설명드리자면 가상돔에서 리스트 component 에서 변경된 부분을 감지할 때 저 key 라는 값을 이용하기 때문에 리스트 렌더링시에는 항상 key
라는 값이 필요합니다.
위에서 알아본 방법을 바탕으로 webtoon component 를 구성해보겠습니다.
Copy // webtoon.vue
<template>
<div>
<h2>Webtoon</h2>
<ul class="wrap">
<li class="item" v-for="(item, idx) in items" :key="{idx}">
<a :href="item.link" target="_blank">
<img :src="item.img">
<span class="tit">제목: {{item.name}}</span>
</a>
</li>
</ul>
</div>
</template>
v-for 를 이용하여 item 리스트를 렌더링 합니다. (item: 객체, idx: 배열의 인덱스), key 값은 인덱스 값을 이용합니다.
:href
, :src
같이 기본 태그에 :
가 붙어 있는걸 볼 수 있습니다. :
가 붙으면 "" 영역이 JS 영역으로 변경됩니다. 그렇기 때문에 item
객체에 접근할 수 있는 것 입니다.
5. 스타일 입히기
Webtoon component 에 style 을 입혀보겠습니다.
Copy // Webtoon.vue
<style scoped>
h2 {
text-align: center;
}
a {
list-style: none;
text-decoration: none;
}
li {
list-style: none;
}
.wrap {
max-width: 450px;
width: 100%;
margin: 0 auto;
}
.item {
border-bottom: 1px solid #ebebeb;
margin-bottom: 25px;
}
.tit {
display: inline-block;
font-size: 18px;
font-weight: bold;
color: #000;
padding: 20px 15px;
}
img {
width: 100%;
background: #ebebeb;
border-radius: 4px;
}
</style>
마무리
v-for
를 이용하여 간단하게 리스트를 렌더링하는 방법을 배워봤습니다.
다음 챕터에는 v-if
, v-show
를 이용하여 조건부 렌더링하는 방법을 알아보겠습니다.
참고: 공식문