v-if

<div v-if="true">True</div>
<div v-if="false">False</div>

v-if는 값이 true이면 렌더링을 하고, false이면 렌더링 하지 않는다.

 

 

v-else

<div v-if="false">True</div>
<div v-else>False</div>

v-else는 v-if와 함께 사용할 수 있다.

앞의 조건이 성립하지 않는다면 else 조건이 동작한다.

 

앞의 조건이 false 이므로 True라는 텍스트는 렌더링되지 않고 False라는 텍스트가 렌더링 된다.

 

v-show

v-show는 v-if와 결과는 같지만 동작하는 방식이 다르다.

v-if는 조건이 false이면 태그 자체를 렌더링하지 않지만 v-show는 렌더링은 하되 display: none 처리를 한다.

 

 

실습)

먼저 업데이트 여부를 판단할 수 있는 값을 추가한다.

(isUpdate를 추가하였다)

// App.vue

<script>
import Webtoon from "./components/Webtoon";

export default {
  components: {
    Webtoon
  },
  data() {
    return {
      webtoons: [
        {
          name: "햄스터와 그녀",
          link: "http://webtoon.daum.net/webtoon/view/hamsterandher",
          img:
            "http://t1.daumcdn.net/webtoon/op/478cdf37f585607982ffa9e35b432e8503be8a54",
          isUpdate: true
        },
        {
          name: "프롬 스타",
          link: "http://webtoon.daum.net/webtoon/view/fromstar",
          img:
            "http://t1.daumcdn.net/webtoon/op/a7fb953d722c1130bfc18440f7e3ce448ece57a1",
          isUpdate: true
        },
        {
          name: "위대한 로맨스",
          link: "http://webtoon.daum.net/webtoon/view/greatromance",
          img:
            "http://t1.daumcdn.net/webtoon/op/a816281cb4df5c50a20ac386fd6e496643d0f085",
          isUpdate: false
        },
        {
          name: "빛나는 손을",
          link: "http://webtoon.daum.net/webtoon/view/Hand",
          img: "http://t1.daumcdn.net/cartoon/5913FCAC0234C50001",
          isUpdate: false
        }
      ]
    };
  }
};
</script>

 

Webtoon.vue에 v-if를 사용하여 isUpdate 값에 따라 태그를 렌더링하도록 한다.

// Webtoon.vue
<template>
  <div>
    <h2>Webtoon</h2>
    <ul class="wrap">
      <li class="item" v-for="(item, idx) in items" :key="{idx}">
        <a :href="item.link" target="_blank">
          <img :src="item.img">
          <span class="tit">제목: {{item.name}}</span>
        </a>
        <span class="tag" v-if="item.isUpdate">N</span>
      </li>
    </ul>
  </div>
</template>

 

스타일을 추가해준다.

<style scoped>
.tag {
  position: absolute;
  left: 10px;
  top: 10px;
  padding: 5px 30px;
  color: #fff;
  border-radius: 4px;
  background: #fc2332;
  font-weight: bold;
}
</style>

isUpdate가 true인 item들에게만 N 이 렌더링 된다.

 

 

 

결론

v-if, v-show는 어떻게 구별해서 사용해야 할까?

상태가 빈번하게 바뀐다면 v-if를 사용했을 때 태그를 그렸다 지웠다 하기 때문에 브라우저에 부담이 생긴다.

따라서 이러한 경우에는 v-show를 사용하고, 보통은 v-if를 사용하는 것을 추천한다.

 

'Vue.js' 카테고리의 다른 글

03 인스턴스 & 컴포넌트 - 뷰 인스턴스  (0) 2022.11.11
Data Binding  (0) 2022.11.03
v-for 를 이용한 리스트 렌더링  (0) 2022.10.26
State와 Props  (0) 2022.10.26
Component 구성해보기  (0) 2022.10.25

+ Recent posts