Vuejs2 기초 - 10 v-for 리스트 렌더링

riverkim·2022년 9월 1일
0
post-thumbnail

10 v-for 리스트 렌더링

v-for은 리스트 렌더링에 주로 사용

v-for로 엘리먼트에 배열 매핑하기
v-for 디렉티브를 사용하여 배열을 기반으로 리스트를 렌더링 할 수 있습니다. v-for 디렉티브는 item in items 형태로 특별한 문법이 필요합니다. 여기서 items는 원본 데이터 배열이고 item은 반복되는 배열 엘리먼트의 별칭 입니다.

v-for을 사용하지 않으면 리스트가 추가될 때마다 하나씩 수동으로 바꿔줘야 한다

<!DOCTYPE html>
<html lang="ko">
<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>v-for</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <div>
            <p>{{students[0].name}} {{students[0].age}}</p>
            <p>{{students[1].name}} {{students[1].age}}</p>
            <p>{{students[2].name}} {{students[2].age}}</p>
        </div>
    </div>
    <script>
        new Vue({
            el:'#app',
            data:{
                students:[
                    {name:'a', age:20},
                    {name:'b', age:21},
                    {name:'c', age:22}
                ]
            }
        })
    </script>
</body>
</html>

v-for 사용 하면 코드중복도 줄여주고 코드량도 줄어든다

<!DOCTYPE html>
<html lang="ko">
<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>v-for</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <div>
            <p>{{students[0].name}} {{students[0].age}}</p>
            <p>{{students[1].name}} {{students[1].age}}</p>
            <p>{{students[2].name}} {{students[2].age}}</p>
        </div>
        <hr>
        <div v-for="student in students">
            <p>{{student.name}} {{student.age}}</p>
        </div>
    </div>
    <script>
        new Vue({
            el:'#app',
            data:{
                students:[
                    {name:'a', age:20},
                    {name:'b', age:21},
                    {name:'c', age:22}
                ]
            }
        })
    </script>
</body>
</html>

결과화면

v-for에 index를 받아서 사용할 수도 있다

<!DOCTYPE html>
<html lang="ko">
<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>v-for</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <div v-for="(student,index) in students">
            <p>{{student.name}} {{student.age}} index: {{index}}</p>
        </div>
    </div>
    <script>
        new Vue({
            el:'#app',
            data:{
                students:[
                    {name:'a', age:20},
                    {name:'b', age:21},
                    {name:'c', age:22}
                ]
            }
        })
    </script>
</body>
</html>

결과화면

리스트에는 key값을 넣어주는걸 권장하는데
key값으로 index를 사용하면 key값이 변경될 가능성이 있어서 index를 key값으로 사용하면 안됨!

객체에도 v-for를 사용할 수 있다.

<!DOCTYPE html>
<html lang="ko">
<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>v-for</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <div v-for="(student, index) in students" :key="student.id" >
           <p> {{student.name}} {{student.age}} index:{{index}}</p>
        </div>
        <hr>
        <div v-for="item in book">
            <p>{{item}}</p>
        </div>
        <hr>
        <div v-for="(value, name) in book">
            <p>{{name}} : {{value}}</p>
        </div>
        <hr>
        <div v-for="(value, name, index) in book">
            <p>{{name}} : {{value}} / index: {{index}}</p>
        </div>
    </div>
    <script>
        new Vue({
            el:'#app',
            data:{
                book:{
                    title:'Hello World',
                    page:800,
                    author:'riverkim'
                },
                students:[
                    {id:0, name:'a', age:20},
                    {id:1, name:'b', age:21},
                    {id:2, name:'c', age:22}
                ]
            }
        })

    </script>
</body>
</html>

필터링 / 정렬 된 결과 표시하기

때로 원본 데이터를 실제로 변경하거나 재설정하지 않고 배열의 필터링 된 버전이나 정렬된 버전을 표시해야 할 필요가 있습니다. 이 경우 필터링 된 배열이나 정렬된 배열을 반환하는 계산된 속성을 만들 수 있습니다.

<!DOCTYPE html>
<html lang="ko">
<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>v-for</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <ul>
            <li v-for="n in evenNumbers">{{n}}</li>
        </ul>
    </div>
    <script>
        new Vue({
            el:'#app',
            data:{
                numbers:[1,2,3,4,5],
            },
            computed:{
                evenNumbers: function(){
                    return this.numbers.filter(function(number){
                        return number % 2 === 0
                    })
                }
            }
        })
    </script>
</body>
</html>

계산된 속성을 실행할 수 없는 상황(예: 중첩 된 v-for 루프 내부)에서는 다음 방법을 사용할 수 있습니다.

<!DOCTYPE html>
<html lang="ko">
<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>v-for</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <ul>
            <li v-for="n in even(numbers)">{{ n }}</li>
        </ul>
    </div>
    <script>
        new Vue({
            el:'#app',
            data: {
            numbers: [ 1, 2, 3, 4, 5 ]
            },
            methods: {
            even: function (numbers) {
                return numbers.filter(function (number) {
                return number % 2 === 0
                })
            }
            }
        })
    </script>
</body>
</html>

Range v-for
v-for 는 숫자를 사용할 수 있습니다. 이 경우 템플릿을 여러번 반복합니다.

<!DOCTYPE html>
<html lang="ko">
<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>v-for</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <div>
            <span v-for="n in 10">{{ n }} </span>
        </div>
    </div>
    <script>
        new Vue({
            el:'#app',
        })
    </script>
</body>
</html>

v-for 와 v-if

v-if 와 v-for 를 동시에 사용하는 것을 추천하지 않습니다. 스타일가이드에서 자세한 내용을 확인하세요.

동일한 노드에 두가지 모두 있다면, v-for가 v-if보다 높은 우선순위를 갖습니다. 즉, v-if는 루프가 반복될 때마다 실행됩니다. 이는 일부 항목만 렌더링 하려는 경우 유용합니다.

profile
Hello!

0개의 댓글