반응형
공식 참고 문서
https://v3.ko.vuejs.org/guide/list.html
리스트 렌더링을 수행하는 여러 방법이 있다.
1. 배열 데이터를 만들어서 사용하는 방법
2. computed 속성을 이용하여 미리 구현된 데이터를 계산하여 리스트를 만드는 방법 (index값을 이용할 수 있다.)
3. shortid 패키지를 이용하여 2번과 같이 리스트를 구현하는 방법
리스트 렌더링을 하기위한 패키지 설치
명령어: npm i -D shortid
스크립트 부분에 import를 해준다
<script>
import shortid from 'shortid'
예제 코드
<template>
<button @click="handler">
click
</button>
--------------------------------------
* 간단한 예제
<ul>
<li
v-for="(f, i) in fruits"
:key="f">
{{ f }} - {{ i+1 }}
</li>
</ul>
-------------------------------------
* 배열을 이용한 리스트 예제
<ul>
<li
v-for="f2 in newFruits"
:key="f2.id">
{{ f2.name }}
</li>
</ul>
--------------------------------------
* 패키지를 이용한 리스트 예제
<ul>
<li
v-for="fruit in newFruits2"
:key="fruit.id">
{{ fruit.name }} - {{ fruit.id }}
</li>
<li
v-for="{id, name} in newFruits2"
:key="id">
{{ name }} - {{ id }}
</li>
</ul>
</template>
<script>
import shortid from 'shortid'
export default {
data() {
return {
fruits: ['Apple', 'Banana', 'Cherry']
}
},
computed: {
newFruits() {
return this.fruits.map((fruit, index) => {
return {
id: index,
name: fruit
}
})
},
// 패키지를 이용한 리스트 구현하기
newFruits2() {
return this.fruits.map(fruit => ({
id: shortid.generate(),
name: fruit
}))
}
},
methods: {
handler() {
// 새로운 데이터를 배열에 추가
this.fruits.push('Orange')
}
}
}
</script>
브라우저 확인
반응형
'프론트엔드 > Vue.js' 카테고리의 다른 글
이벤트 핸들링 - 이벤트 수식어 (0) | 2021.07.31 |
---|---|
이벤트 핸들링 (0) | 2021.07.29 |
조건부 렌더링 (0) | 2021.07.28 |
v-model 수식어 예제 (0) | 2021.07.27 |
클래스와 스타일 바인딩 (0) | 2021.07.27 |