📌V-for 반복문
v-for="작명" in "반복할 횟수" :key="작명"
상단 메뉴바 3개를 for문을 이용해 출력해보자
<a v-for="작명 in 3" :key="작명">Home</a>
라고 작성하면 된다. 작명은 아무 작명하면 된다!
<template>
<!-- 상단 메뉴 -->
<div class="menu">
<a v-for="작명 in 3" :key="작명">Home</a> <!-- Home 3개 출력 -->
<!--<a>Products</a>-->
<!--<a>About</a>-->
</div>
<!-- // 상단 메뉴 끝 -->
<div>
<h4>{{products[0]}}</h4>
<p>10만원</p>
</div>
<div>
<h4>{{products[1]}}</h4>
<p>20만원</p>
</div>
<div>
<h4>{{products[2]}}</h4>
<p>30만원</p>
</div>
</template>
v-for 반복문에 array, object 데이터를 넣으려면?
먼저 데이터 보관소에 데이터를 등록하자.
menu 라는 데이터를 등록했다.
<script>
export default {
name: 'App',
data() {
return {
products : ['역삼동원룸', '천호동원룸', '마포구원룸'],
menu : ['Home', 'Shop', 'About']
}
},
components: {
}
}
</script>
<template>
<!-- 상단 메뉴 -->
<div class="menu">
<a v-for="a in menu" :key="a">{{a}}</a>
<!--<a>Products</a>-->
<!--<a>About</a>-->
</div>
<!-- // 상단 메뉴 끝 -->
<div>
<h4>{{products[0]}}</h4>
<p>10만원</p>
</div>
<div>
<h4>{{products[1]}}</h4>
<p>20만원</p>
</div>
<div>
<h4>{{products[2]}}</h4>
<p>30만원</p>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
products : ['역삼동원룸', '천호동원룸', '마포구원룸'],
menu : ['Home', 'Shop', 'About']
}
},
components: {
}
}
</script>
data 보관소에 등록했으면 <template> 영역에 v-for 을 이용해보자.
<a v-for="a in menu" :key="a">{{a}}</a>
a는 아무 작명이나 하면돼서 편의상 a로 하였다. b로해도 되고 c로해도 된다.
'menu' 는 밑에서 등록한 데이터 이름이다.
menu는 Array 형태이다.
a in menu 라 함은 menu 라는 Array 안의 데이터를 한개씩 차례대로 방문한다고 이해하면 된다.
첫번째 for 문을 돌 때의 a 는 'Home' 이 되는 것이고 두 번째 for 문을 돌 때의 a 는 'Shop'이 된다.
(for 문은 menu 의 자료 갯수만큼 반복된다)
그러면 메뉴바에서 Home, Shop, About 순서대로 노출시키고 싶다면 {{a}} 로 노출 시킬 수 있다.
v-for 안의 변수는 2개까지 작명 가능하다.
<a v-for="(작명,i) in menu" :key="i"> {{ 작명 }}</a>
첫째 작명: array 안의 데이터
둘째 작명: array 의 인덱스 (0,1, 2, ... 이런식으로 1씩 증가하는 정수) => 반복 횟수 알려주는 숫자
i 를 출력해보면 0,1,2 로 출력된다.
작명이 두 개일 땐 관습적으로 둘째 작명(i) 를 key 에 넣는다.
'Vue3 > 코딩애플 part1' 카테고리의 다른 글
[Vue/코딩애플/part1] 5. 실제 데이터 넣어 상품 목록 만들기 (import / export) (0) | 2024.07.26 |
---|---|
[Vue/코딩애플/part1] 4. Vue 에서 모달창 만들기 (0) | 2024.07.24 |
[Vue/코딩애플/part1] 3. 이벤트 핸들러로 click 감지하기 (2) | 2024.07.24 |
[Vue/코딩애플/part1] 1. HTML에 자바스크립트 데이터 넣기 (Vue 데이터 바인딩 문법) (0) | 2024.07.24 |
[Vue/코딩애플/part1] 0. vue 개발 환경 셋팅 (0) | 2024.07.18 |