react+vue

[vue]v-for 조건부 랜더링(template태그)

h-yujin 2022. 11. 9. 14:20

조건부 렌더링

v-if와 v-for는 함께 사용할 수 없다

<template>
  <div>
    <h2 v-if="animal!=='monkey'"v-for="(animal,index) in animals" :key="index">{{index}}:{{animal}}</h2>
  </div>
</template>

<script>

export default {
  name: 'App',
  data: ()=>{
    return {
      animals:["monkey","rat","dog","lion"]
    };
  }
}
</script>

  • 태그를 중첩시키는 방법
<template>
  <div>
    <h2 v-for="(animal,index) in animals" :key="index">
      <span v-if="animal!=='monkey'">{{index}}:{{animal}}</span>
    </h2>
  </div>
</template>

<script>

export default {
  name: 'App',
  data: ()=>{
    return {
      animals:["monkey","rat","dog","lion"]
    };
  }
}
</script>

h2와 span태그가 반복되는 만큼 생성되어 비효율적이다.

  • template 태그 사용

<template>
  <div>
    <template v-for="(animal,index) in animals" :key="index">
      <h2 v-if="animal!=='monkey'">{{index}}:{{animal}}</h2>
    </template>
  </div>
</template>

<script>

export default {
  name: 'App',
  data: ()=>{
    return {
      animals:["monkey","rat","dog","lion"]
    };
  }
}
</script>

중첩태그 없이 필요한 개수만큼 태그가 생성된다.