완벽하게 Vue.js
[Vue.js][Ch2][Vue 문법] 리스트 렌더링
써치킴
2022. 4. 4. 04:18
App.vue
<template>
<ul>
<li
v-for="(fruit, index) in fruits"
:key="fruit">
{{ fruit }}-{{ index + 1 }}
</li>
<br/> <!-- 위 아래 같은 li 태그임 -->
<li
v-for="(f, i) in fruits"
:key="f">
{{ f }}-{{ i + 1}}
</li>
<br/>
<li
v-for="fruit in newFruits"
:key="fruit.id">
{{ fruit }} <br/>
{{ fruit.id }} - {{ fruit.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
fruits: ['Apple', 'Banana', 'Cherry']
}
},
computed: {
newFruits() {
return this.fruits.map((fruit, index) => { // 배열 데이터 반환
return { // 객체 데이터 반환
id: index,
name: fruit
}
})
}
}
}
</script>
출력
배열의 각각 아이템을 고유하게 구분해줄 수 있는 특정한 속성을 통해(ex.id) 화면에 출력되는 내용을 최적화할 수 있다.
=> 각각의 아이템을 고유하게 만들 수 있는 패키지를 설치해보자 : shortid 패키지
npm i -D shortid
App.vue
<template>
<button @click="handler">
Click me!
</button>
<ul>
<li
v-for="fruit in newFruits"
:key="fruit.id">
{{ fruit.id }} - {{ fruit.name }}
</li>
<br/>
<!-- 객체구조분해하여 id, name 직접적으로 사용 가능 -->
<li
v-for="{ id, name } in newFruits"
:key="id">
{{ id }} - {{ name }}
</li>
</ul>
</template>
<script>
import shortid from 'shortid'
export default {
data() {
return {
fruits: ['Apple', 'Banana', 'Cherry']
}
},
computed: {
newFruits() {
return this.fruits.map(fruit => ({ // 객체 데이터 반환
/* shortid.generate()
: 간단한 id를 생성해주는 메서드
, 고유한 형태의 id를 만들기 위해 사용
*/
id: shortid.generate(),
name: fruit
}))
}
},
methods: {
handler() {
this.fruits.push('orange');
}
}
}
</script>
출력
데이터를 갱신하면 화면이 바뀐다 => 반응성
배열 변경 감지
Vue는 감시중인 배열의 변이 메소드를 래핑하여 뷰 갱신을 트리거한다.
: '배열 데이터를 변경하면 화면이 갱신되어 출력한다.' 라는 뜻이다.
래핑 메소드
- push()
- pop()
- shift()
- unshift()
- splice()
- sort()
- reverse()
배열 교체
변이 메소드는 호출된 원래 배열을 변경한다.
이에 비해 filter(), concat() and slice()와 같은 원래 배열을 변경하지는 않지만 항상 새 배열을 반환하는 비-변이 메소드도 있다.
비-변이 메소드로 작업할 때 이전 배열을 새 배열로 바꿀 수 있다.
example1.items = example1.items.filter(item => item.message.match(/Foo/))