본문 바로가기

Vue.js

Kossie Coder 10. v-for 리스트 렌더링

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
    <!--이렇게 하나하나 적게되면 peope배열이 변경되어도 업데이트가 안된다.-->
        <div>
            {{people[0].name}} {{people[0].age}}
        </div>
        <div>
            {{people[1].name}} {{people[1].age}}
        </div>
        <div>
            {{people[2].name}} {{people[2].age}}
        </div>
        <div>
            {{people[3].name}} {{people[3].age}}
        </div>
        <hr>
        <div v-for="person in people">{{person["name"]}} {{person["age"]}}</div>
        <!--v-for를 하게되면 추가될때 자동으로 업데이트가 된다.-->
        <!--v-for in 을 써도 되고, of를 써도 똑같은 결과가 나온다.-->
        
        <div v-for="(person, index) in people" :key="person.name+'-'+person.age">{{person["name"]}} {{person["age"]}} {{index}}</div>
        <!--괄호치고 index를 하면 index를 가져올 수 있다.-->
        <!--v-for의 각 항목들에 고유한 key속성을 필수적으로 제공해야. key값은 유니크한 값이어야 한다.-->
        <!-- 만약 name이 unique하지 않으면, 다른 값과 합해서 유니크한 값을 만들 수 있다. -->
        <!-- key에 index를 넣게되면, 만약 data가 사라지면 Index값이 바뀌기 때문에 좋지않다. -->
        <!-- v-for를 객체에서도 사용할 수 있다. -->
    </div>

<script>
   new Vue({
      el: '#app',
      data: { 
          people: [
              {name: 'a', age: 20},
              {name: 'b', age: 21},
              {name: 'c', age: 22},
              {name: 'd', age: 23},
              {name: 'e', age: 24},
          ],
      },
      methods: {
      },
      computed: {
      },
      watch: {
      }
    })
</script>
</body>
</html>

1/ v-for을 사용하지 않으면 배열에 요소가 추가되어도 업데이트되지 않는다.

2/ v-for in을 사용해도 되고, v-for of를 사용해도 똑같은 결과가 나온다.

3/ v-for="(person, index)" 이렇게 괄호치고 index를 하면 index를 가져올 수 있다.

4/ v-for의 각 항목들에 고유한 key속성을 필수적으로 줘야한다. key값은 유니크한 값!

5/ :key="person.name" 이렇게 적을 경우, name이 unique하지 않으면 다른 값과 합해서 unique한 값을 만들 수 있다.

6/ v-for는 객체에서도 사용 가능