티스토리 뷰

728x90
 

Class & Style Binding - Intro to Vue.js | Vue Mastery

In this lesson we’ll be learning how to dynamically style our HTML by binding data to an element’s style attribute, as well as its class.

www.vuemastery.com

v-bind: 축약인 : 에 class, style을 데이터 상태에 따라 노출하게 할 수 있다.

 

양말의 색상을 글자에서 색상으로 변경하는 기능과 재고가 없을 경우 Add to cart 버튼을 disabled 시키고 회색 버튼으로 노출하는 기능을 구현하면 다음과 같다.

 

<!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 v-bind: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 > 0">In Stock</p>
                <p v-else>Out of Stock</p>

                <ul>
                    <li v-for="detail in details">{{ detail }}</li>
                </ul>

                <div class="color-box"
                    v-for="variant in variants" 
                    :key="variant.variantId"
                    :style="{backgroundColor: variant.variantColor}"
                    @mouseover="updateProduct(variant.variantImage)"
                    >
                </div>

                <button v-on:click="addToCart"
                :disabled="!inStock"
                :class="{ disabledButton: !inStock }"
                >Add to cart</button>
                <div class="cart">
                    <p>Cart({{ cart }})</p>
                </div>
            </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: false,
        isStock: false,
        details: ["80% cotton", "20% polyester", "Gender-neutral" ],
        variants: [
            {
                variantId: 2234,
                variantColor: "green",
                variantImage: "./assets/vmSocks-green-onWhite.jpg",
            },
            {
                variantId: 2235,
                variantColor: "blue",
                variantImage: "./assets/vmSocks-blue-onWhite.jpg",
            }
        ],
        cart: 0,
    },
    methods: {
        addToCart(){
            this.cart +=1
        },
        updateProduct(variantImage){
            this.image = variantImage
        }
    }
})

728x90
댓글