JSFiddle - React, Tailwind, and code Playground
by SUNGMIN SHIN
HTML
<template id="food">
<div>
<span>{{ votes }}</span>
<!-- v-on(@)을 통해 click시 vote(voted내부에서는 voted를 실행)가 실행되도록 설정 -->
<button @click="vote">{{ name }}</button>
</div>
</template>
<!-- // #food -->
<div id="container">
<p>
{{ votes }}
</p>
<!-- voted를 countVote로 설정 -->
<div class="btn_area">
<food name="치즈버거" @voted='countVote'></food>
<food name="더블베이컨버거" @voted='countVote'></food>
<food name="로데오버거" @voted='countVote'></food>
</div>
<div class="log_area">
<ul>
<li v-for="vote in log">
{{vote}}
</li>
</ul>
</div>
</div>
<!-- // #container -->
JavaScript
// #food
Vue.component('food', {
template: '#food',
props: ['name'],
data: function() {
return {
votes: 0
}
},
methods: {
vote: function(event) {
var btnName = event.srcElement.textContent;
this.votes++;
// 인스턴스 이벤트 $emit을 통해 'voted'를 실행(voted의 위치를 유심히 볼 것)
this.$emit('voted', btnName);
}
}
})
new Vue({
el: '#container',
data: {
votes: 0,
log: []
},
methods: {
countVote: function(name) {
console.log(name);
this.log.push(`${name}가 투표되었습니다.`);
this.votes++
}
}
})