티스토리 뷰

728x90

 

이벤트가 발생했을 때 수행되어야 하는 메서드와 연결하는 방법을 배웁니다.

 

 

Event Handling - Intro to Vue.js | Vue Mastery

In this lesson we’ll be learning how to listen for DOM events that we can use to trigger methods.

www.vuemastery.com

v-on:이벤트명 = "메소드명"  태그에 추가합니다.

<!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 v-for="variant in variants" :key="variant.variantId">
                    <p @mouseover="updateProduct(variant.variantImage)">{{ variant.variantColor }}</p>
                </div>

                <button v-on:click="addToCart">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>

Add to cart 버튼이 눌리면 Cart 개수가 늘어나는 것을 확인해 볼 수 있습니다.

v-on: 는 @로 축약해서 사용가능합니다. 앞서 양말의 색상 목록을 보여주는 기능을 구현했는데 각각의 색상에 moseover 하면 해당 이미지로 업데이트해주는 기능을 updateProduct로 구현하였습니다.

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,
        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
댓글