[Vue3] 8. 리스트 랜더링

김관응·2023년 4월 7일
0

Vue

목록 보기
9/14
post-thumbnail

v-for

v-for 디렉티브를 이용해 배열을 리스트로 랜더링 할 수 있다.

<template>
  <li v-for="item, idx in items">
    {{ idx }} : {{ item.message }}
  </li>
</template>

<script setup>
const items = ref([{ message: 'Foo' }, { message: 'Bar' }])
</script>

items라는 배열에서 한개식 꺼내서 item에 담아 표현 해주고, idx는 배열의 순서를 나타낸다.

for를 중첩으로도 사용이 가능하다.

v-for 속성 객체로 이용하기

객체의 속성들을 반복하는데에도 v-for를 사용할 수 있다.

<template>
  <li v-for="(value, key, index) in myObject">
    {{ index }}. {{ key }}: {{ value }}
  </li>
</template>

<script setup>
const myObject = reactive({
  title: 'Vue에서 목록을 작성하는 방법',
  author: '홍길동',
  publishedAt: '2023-04-07'
})
</script>

순서대로 value, key, index를 뽑아다 사용할 수 있다.

v-for 숫자 범위로 이용하기

<span v-for="n in 10">{{ n }}</span>

n은 1부터 시작을 하고 10까지 출력하게된다.

기타

template 태그에다가도 v-for를 사용 가능하다.
(예를들면 역할별로 화면을 다르게 만들어야 하는 경우)

컴포넌트도 동일하게 v-for를 통해 반복할 수 있다.

filter

원본 데이터에서 필요한 데이터만 걸러낼 때 사용한다.

<template>
  <li v-for="n in evenNumbers">{{ n }}</li>
</template>

<script setup>
const numbers = ref([1, 2, 3, 4, 5])

const evenNumbers = computed(() => {
  return numbers.value.filter((n) => n % 2 === 0)
})
</script>

1, 2, 3, 4, 5 배열 중 2로나눈 나머지가 0인것만 리턴해준다.

profile
엔지니어였던 개발자

0개의 댓글