[Vue] 3장 리스트와 키

1. 리스트 렌더링

Vue.js에서 리스트를 렌더링할 때는 v-for 디렉티브를 사용해 배열이나 객체를 반복할 수 있습니다. 이 때 각 항목에 대해 고유한 key 속성을 사용하는 것이 중요합니다. key 속성은 Vue가 각 항목의 변경 사항을 추적하고 성능을 최적화하는 데 도움을 주는 렌더링 입니다.

<template>
  <ListRender />
</template>

<script>
import ListRender from './components/List/ListRender.vue'

export default {
  name: 'App',
  components: {
    ListRender,
  },
  data() {
    return {
      parentMessage: 'Hello, World ',
    }
  },
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
<template>
  <ul>
    <li v-for="item in items" :key="item.id">{{ item.name }}</li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'item1' },
        { id: 2, name: 'item2' },
        { id: 3, name: 'item3' },
      ],
    }
  },
}
</script>
  • key 속성의 중요성
    • key 속성은 리스트의 각 항목을 식별하는 데 사용됩니다. Vue는 이 key를 사용해 항목의 추가, 삭제 및 변경을 효율적으로 처리
    • 일반적으로 항목의 고유한 ID를 사용하는 것이 좋음

2. Key 속성을 사용하지 않을 경우의 문제

아래와 같이 Key 속성을 사용하지 않으면 Vue의 항목의 변경 사항을 효율적으로 추적하지 못할 수 있으며, 이로 인해 성능 저하나 예기치 않은 동작이 발생할 수 있습니다.

<template>
  <ul>
    <li v-for="item in items">{{ item.name }}</li>
  </ul>
</template>

3.동적 리스트와 Key

List와 Key의 항목 추가와 삭제를 하려면 아래와 같이 작성하면 됩니다.

<template>
  <div>
    <ul>
      <li v-for="item in items" :key="item.id">{{ item.name }}</li>
    </ul>
    <button @click="addItem">Add Item</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'item 1' },
        { id: 2, name: 'item 2' },
      ],
    }
  },
  methods: {
    addItem() {
      const newId = this.items.length + 1
      this.items.push({ id: newId, name: `item ${newId}` })
    },
  },
}
</script>

 

GitHub - Koras02/vue-tutorial: https://thinky.tistory.com/category/Front-End/VueJS

https://thinky.tistory.com/category/Front-End/VueJS - Koras02/vue-tutorial

github.com

 

LIST

'Front-End > VueJS' 카테고리의 다른 글

[Vue] 6장(완) API 통신  (0) 2025.03.16
[Vue] 5장 상태관리  (0) 2025.03.08
[Vue] 4장 라우팅  (0) 2025.03.05
[Vue] 2장 기본 컴포넌트  (0) 2025.02.23
[Vue] 1장 Vue란 무엇인가?  (0) 2025.02.23