티스토리 뷰

Library | Framework/Vue JS

[Vue.js] 4. 이벤트핸들러

공부하는 승승 2023. 8. 3. 01:52

 

클릭 이벤트

<!-- v-on:의 축약: @ -->
<button v-on:click="더하기">버튼</button
<button @click="더하기">버튼</button>

 

ex) 버튼 누르면 숫자 증가시키기

<template>
    <button @click="increase++">1증가버튼</button> // click하면
    <span>{{ increase }}</span> // 초기값 0이 +1
</template>

<script>
export default {
    name: 'App',
    data() {
        return {
            increase: 0,
        };
    },
    components: {},
};
</script>

 

코드가 길 땐 함수로 작성하기

<template>
    <button @click="increase()">1증가버튼</button> <!-- 클릭 시 함수() 실행 -->
    <span>{{ increase }}</span>
</template>

<script>
export default {
    name: 'App',
    data() {
        return {
            increase: 0,
        };
    },
    methods: {
        increase() {
            this.report++; // 데이터 사용 시 this.붙여주기
        },
    },
    components: {},
};
</script>

 

반복문과 함께 사용하기

<template>
    <div v-for="(a, i) in products" :key="i">
        <button @click="increase[i]++">1증가버튼</button> // click하면
        <span>{{ increase[i] }}</span> // 초기값 0이 +1
    </div>
</template>

<script>
export default {
    name: 'App',
    data() {
        return {
            report: [0, 0, 0], // 0번째버튼값, 1번째버튼값, 2번째버튼값
        };
    },
    components: {},
};
</script>

 

댓글