[개발] 프로그램 지식

Vue.js 입문 가이드: v-for 지시문 사용법

  • -
반응형
Vue.js 입문 가이드: v-for 지시문 사용법

Vue.js 입문 가이드: v-for 지시문 사용법

일반적인 배열 기반 HTML 요소 생성

일반적인 JavaScript를 사용하면 배열을 기반으로 HTML 요소를 생성할 수 있습니다. for-loop를 사용하고 내부에서 요소를 생성하고 조정한 다음 각 요소를 페이지에 추가해야 합니다. 그러나 이러한 요소는 배열 변경에 반응하지 않습니다.

Vue의 v-for 지시문

Vue를 사용하면 속성 v-for를 사용하여 목록에 생성하려는 HTML 요소로 시작하여 Vue 인스턴스 내부의 배열을 참조하고 나머지는 Vue가 처리하도록 합니다. v-for로 생성된 요소는 배열이 변경되면 자동으로 업데이트됩니다.

목록 렌더링 예제

아래 예제는 v-for를 사용하여 Vue 인스턴스 배열의 각 음식 항목에 대한 <li> 태그를 생성합니다.

<!DOCTYPE html>
<html>
<head>
  <title>My first Vue page</title>
  <style>
    #app > div {
      border: solid black 1px;
      width: 80%;
      padding: 10px;
      display: flex;
      flex-wrap: wrap;
    }
    img {
      width: 70px;
      margin: 10px;
    }
  </style>
</head>
<body>

<h1>Example: 'v-for' to create li-tags</h1>

<p>In this example 'v-for' creates an 'li' tag with the food name for each food item in the Vue instance array.</p>

<div id="app">

  <ol>
    <li v-for="x in manyFoods">{{ x }}</li>
  </ol>

</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<script>
  const app = Vue.createApp({
   data() {
    return {
      manyFoods: [
        'Burrito',
        'Salad',
        'Cake',
        'Soup',
        'Fish',
        'Pizza',
        'Rice'
      ]
    }
   }
  })
  
  app.mount('#app')

</script>

</body>
</html>

이미지 생성 예제

아래 예제는 v-for 지시문을 사용하여 Vue 인스턴스의 배열을 기반으로 이미지를 생성합니다.

<!DOCTYPE html>
<html>
<head>
  <title>My first Vue page</title>
  <style>
    #app > div {
      border: solid black 1px;
      width: 80%;
      padding: 10px;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
    }
    img {
      width: 70px;
      margin: 10px;
    }
  </style>
</head>
<body>

<h1>Example 'v-for' to create images</h1>
<p>The 'v-for' directive is used to create images based on the 'manyFoods' array in the Vue instance.</p>

<div id="app">

  <div>
    <img v-for="x in manyFoods" v-bind:src="x">
  </div>

</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<script>
  const app = Vue.createApp({
   data() {
    return {
      manyFoods: [
        'img_burrito.svg',
        'img_salad.svg',
        'img_cake.svg',
        'img_soup.svg',
        'img_fish.svg',
        'img_pizza.svg',
        'img_rice.svg'
      ]
    }
   }
  })
  
  app.mount('#app')

</script>

</body>
</html>

객체 배열을 통한 루프 예제

아래 예제는 v-for 지시문을 사용하여 Vue 인스턴스의 객체 배열을 기반으로 이미지와 텍스트를 생성합니다.

<!DOCTYPE html>
<html>
<head>
  <title>My first Vue page</title>
  <style>
    #app > div {
      border: solid black 1px;
      width: 80%;
      padding: 10px;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
    }

    figure {
      width: 80px;
      padding: 10px;
      margin: 10px;
      background-color: lightskyblue;
      border-radius: 5px;
    }

    figcaption {
      text-align: center;
    }
    
    img {
      width: 100%;
    }
  </style>
</head>
<body>

<h1>Example 'v-for' to create images and text</h1>
<p>The 'v-for' directive is used to create images and text based on the 'manyFoods' array in the Vue instance.</p>

<div id="app">
  <div>
    <figure v-for="x in manyFoods">
      <img v-bind:src="x.url">
      <figcaption>{{ x.name }}</figcaption>
    </figure>
  </div>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<script>
  const app = Vue.createApp({
   data() {
    return {
      manyFoods: [
        {name: 'Burrito', url: 'img_burrito.svg'},
        {name: 'Salad', url: 'img_salad.svg'},
        {name: 'Cake', url: 'img_cake.svg'},
        {name: 'Soup', url: 'img_soup.svg'},
        {name: 'Fish', url: 'img_fish.svg'},
        {name: 'Pizza', url: 'img_pizza.svg'},
        {name: 'Rice', url: 'img_rice.svg'}
      ]
    }
   }
  })
  
  app.mount('#app')

</script>

</body>
</html>

색인 가져오기 예제

아래 예제는 v-for 지시문을 사용하여 배열 요소의 인덱스 번호와 배열 요소를 함께 가져오는 방법을 보여줍니다.

<!DOCTYPE html>
<html>
<head>
  <title>My first Vue page</title>
  <style>
    #app > div {
      display: inline-block;
      border: dashed black 1px;
      padding: 10px;
      background-color: lightgreen;
    }
    #app p {
      font-weight: bold;
      margin: 5px 0;
    }
  </style>
</head>
<body>

<h1>Example: Get the array element index with 'v-for'</h1>
<p>The 'v-for' directive is used to get the index and food name of elements inside the 'manyFoods' array in the Vue instance.</p>

<div id="app">
  <div>
    <p v-for="(x, index) in manyFoods">
      {{ index }}: "{{ x }}" <br>
    </p>
  </div>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<script>
  const app = Vue.createApp({
   data() {
    return {
      manyFoods: [
        'Burrito',
        'Salad',
        'Cake',
        'Soup',
        'Fish',
        'Pizza',
        'Rice'
      ]
    }
   }
  })
  
  app.mount('#app')

</script>

</body>
</html>

객체 배열의 색인 가져오기 예제

아래 예제는 v-for 지시문을 사용하여 객체 배열 요소의 인덱스 번호와 배열 요소의 속성을 함께 가져오는 방법을 보여줍니다.

<!DOCTYPE html>
<html>
<head>
  <title>My first Vue page</title>
  <style>
    #app > div {
      display: inline-block;
      border: dashed black 1px;
      padding: 10px;
      background-color: lightgreen;
    }
    #app p {
      font-weight: bold;
      margin: 5px 0;
    }
  </style>
</head>
<body>

<h1>Example: Get the array element index with 'v-for'</h1>
<p>The 'v-for' directive is used to get the index of objects inside the 'manyFoods' array, together with the name and url of each food object.</p>

<div id="app">
  <div>
    <p v-for="(x, index) in manyFoods">
      {{ index }}: "{{ x.name }}", url: "{{ x.url }}" <br>
    </p>
  </div>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<script>
  const app = Vue.createApp({
   data() {
    return {
      manyFoods: [
        {name: 'Burrito', url: 'img_burrito.svg'},
        {name: 'Salad', url: 'img_salad.svg'},
        {name: 'Cake', url: 'img_cake.svg'},
        {name: 'Soup', url: 'img_soup.svg'},
        {name: 'Fish', url: 'img_fish.svg'},
        {name: 'Pizza', url: 'img_pizza.svg'},
        {name: 'Rice', url: 'img_rice.svg'}
      ]
    }
   }
  })
  
  app.mount('#app')

</script>

</body>
</html>

결론

v-for 지시문은 배열을 기반으로 동적 HTML 요소를 생성하는 데 매우 유용합니다. 이 글에서 소개한 예제를 통해 v-for 지시문의 기본 사용법을 익히고 다양한 상황에 적용할 수 있습니다. Vue.js를 사용하여 더욱 효율적이고 반응형 웹 애플리케이션을 개발해 보세요.

참고 자료

이 글이 유용했다면 좋아요와 공유 부탁드립니다! 더 많은 웹 개발 관련 정보는 저희 블로그에서 확인하세요.

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.