Front-end/Vue

Vue3 기초: 리스트 렌더링

somlang_bba 2022. 2. 16. 00:23
728x90

 

v-for를 이용하여 반복문을 사용할 수 있다.

 

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

<script>
export default {
  name: "App",
  data() {
    return {
      fruits: ["banana", "strawberry", "apple", "melon"],
      user: {
        name: "kj",
        age: 33,
        job: "programmer",
       }
     }
   },
};
</script>

<style></style>

템플릿의 맨 윗부분에  머스태치 문법을 이용하여 배열을  바로 그리면 배열 자체로 나온다.

하지만 아래 li태그에 v-for와 같은 코드로 아래와 같이 화면에 반복적으로 그려줄 수 있다.

특이한건 bind되어있는 key속성인데, vue2에서와 vue3에서의 사용법이 살짝 다르지만 지금은 고유값(key)을 바탕으로 Vue의 가상 DOM트리에서 사용되는 값이라는 점 정도만 알고 지나가면 된다.

 

vue2와 vue3에서의 key속성 차이를 알고 싶다면 여기서 확인하자

https://v3.ko.vuejs.org/guide/migration/key-attribute.html#%E1%84%87%E1%85%A2%E1%84%80%E1%85%A7%E1%86%BC

 

key 속성 | Vue.js

key 속성 개요 NEW: Vue가 고유한 key를 자동으로 생성하기 때문에 v-if/v-else/v-else-if에서 더이상 key가 필요하지 않습니다. BREAKING: 수동으로 key를 정할 경우, 각 분기는 반드시 고유한 key를 사용해야

v3.ko.vuejs.org

 

 

v-for 속성은 배열에서만 사용 가능한 것이 아니고 Object에서도 사용이 가능하다.

<template>
  <div v-for="(animal, animalIndex) in animals" :key="animalIndex">
    <h2>Animal ===> {{ animal.name }}</h2>
    <h3>food</h3>
    <ul>
      <li v-for="(food, foodIndex) in animal.foods" :key="foodIndex">
        {{ food }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      animals: [
        { name: "monkey", size: "medium", foods: ["banana", "apple"] },
        { name: "lion", size: "big", foods: ["deer", "cow"] },
        { name: "rat", size: "small", foods: ["cheese", "rice"] },
      ],
    };
  },
};
</script>

<style></style>

위와 같은 코드를 통해 배열을 반복적으로 그려주면서 객체 안에 있는 내용도 반복해서 그려줄 수 있다.

 

 

728x90