리스트 렌더링

토리최고·2022년 1월 16일
0

Vue 문법

목록 보기
9/20
post-thumbnail

리스트 렌더링

v-for로 엘리먼트에 배열 매핑하기
배열데이터를 반복할 때, 숫자 데이터가 필요하다고 한다면 index 추가

<template>
  <ul>
    <li
      v-for="(fruit, index) in fruits"
      :key="fruit">
      {{ fruit }} - {{ index+1 }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      fruits: ['Apple', 'Banana', 'Cherry']
    }
  }
}
</script>

<style>

</style>

상태 유지

다양한 배열 데이터 활용, 반복적으로 화면에 출력하는 방법
v-for를 통해 id 속성이 아니더라도 item을 구분해주는 특성한 속성이 존재해야하고 그 속성을 통해 배열아이템을 고유하게 구분할 수 있어야한다.

<template>
  <ul>
    <li
      v-for="fruit in newFruits"
      :key="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>

<style>

</style>

shortid

고유한 id가 필요할 때 쓸수있는 패키지

<template>
  <ul>
    <li
      v-for="fruit in newFruits"
      :key="fruit.id">
      {{ fruit.name }}-{{ fruit.id }}
    </li>
  </ul>
</template>

<script>
import shortid from 'shortid'

export default {
  data() {
    return {
      fruits: ['Apple', 'Banana', 'Cherry'],
    }
  },
  computed: {
    newFruits() {
      return this.fruits.map(fruit =>({
        id: shortid.generate(),
        name: fruit
      }))
    }
  }
}
</script>

<style>

</style>

객체 구조 분해

객체 구조 분해를 통해 바로 id와 name 값을 사용할 수 있다.

<template>
  <ul>
    <li
      v-for="{id, name } in newFruits"
      :key="id">
      {{ name }}-{{ id }}
    </li>
  </ul>
</template>

변이 메소드

Vue는 감시중인 배열의 변이 메소드를 래핑하여 뷰 갱신을 트리거합니다. 래핑된 메소드는 다음과 같습니다.

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

배열 교체

이름에서 알 수 있듯이 변이 메소드는 호출된 원래 배열(원본의 배열)을 변경합니다. 이에 비해 filter(), concat() and slice()와 같은 원래 배열을 변경하지는 않지만 항상 새 배열을 반환하는 비-변이 메소드도 있습니다. 비-변이 메소드로 작업할 때 이전 배열을 새 배열로 바꿀 수 있습니다.
이로 인해 Vue가 기존 DOM(HTML)을 버리고 전체 목록을 다시 렌더링할 것이라고 생각할 수 있습니다. 다행히도 그렇지 않습니다. 재사용을 하기위해 똑똑한 방식으로 구현하므로 매우 효율적인 작업입니다.

0개의 댓글

관련 채용 정보