티스토리 뷰

728x90

 

 

Conditional Rendering - Intro to Vue.js | Vue Mastery

In this lesson we’ll be uncovering how to conditionally display elements with Vue.

www.vuemastery.com

html 태그에 v-if, v-else, v-else-if 지시어로 데이터 상태에 따라 노출 여부를 결정할 수 있다. 아래 예제에서 inventory 값을 조건에 맞게 바꾸면 각 조건에 맞는 메시지가 노출된다.

<!DOCTYPE html>
<html>
    <head>
        <title>App</title>
        <link rel="stylesheet" type="text/css" href="./style.css">
    </head>
    <body>
        <div class="nav-bar"></div>
        <div id="app">
            <div class="product">
                <div class="product-image">
                    <img :src="image" :alt="altText"/>
                </div>
            </div>
            <div class="product-info">
                <h1>{{ product }}</h1><span v-show="onSale">On Sale!</span>
                <p>{{ description }}</p>
                <p v-if="inventory > 10">In Stock</p>
                <p v-else-if="inventory <= 10 && inventory > 0">Almost sold out!</p>
                <p v-else>Out of Stock</p>
            </div>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script src="main.js"></script>
    </body>
</html>
var app = new Vue({
    el: '#app',
    data: {
        product: 'Socks',
        description: 'A pair of warm, fuzzy socks',
        image:"./assets/vmSocks-green-onWhite.jpg",
        altText: "A pair of socks",
        inventory: 100,
        onSale: true,
    }
})

또한 v-show 지시어로 해당 데이터가 true 경우에만 노출하도록 할 수 있는데 false 값일 때 html 코드를 보면 display:none 상태로 바뀐다.

 

728x90
댓글