Skip to content

Instantly share code, notes, and snippets.

@allysonsilva
Created December 2, 2017 04:15
Show Gist options
  • Save allysonsilva/cab905e092af225be64eb6e790dfa1d1 to your computer and use it in GitHub Desktop.
Save allysonsilva/cab905e092af225be64eb6e790dfa1d1 to your computer and use it in GitHub Desktop.
Vue.js ⚡️ Event Bus
var bus = new Vue();
Vue.component('food', {
template: '#food',
props: ['name'],
data: function() {
return {
votes: 0
}
},
methods: {
vote: function(event) {
// instead of using this.name
// we can access event's element's text
bus.$emit('voted', event.srcElement.textContent)
this.votes++
},
reset: function() {
this.votes = 0
}
},
created() {
bus.$on('reset', this.reset)
}
});
new Vue({
el: '#app',
data: {
votes: {
count: 0,
log: []
}
},
methods:
{
countVote: function(food) {
this.votes.count++
this.votes.log.push(food + ' received a vote.')
},
reset: function() {
this.votes = {
count: 0,
log: []
}
bus.$emit('reset')
}
},
created() {
bus.$on('voted', this.countVote)
}
});
<template id="food">
<div>
<h2> {{ votes }} </h2>
<button @click="vote">{{ name }}</button>
</div>
</template>
<div id="app">
<h1>Food Battle</h1>
<h1> {{ votes.count }} </h1>
<button @click="reset">Reset votes</button>
<hr>
<div>
<food name="Cheeseburger"></food>
<food name="Double Bacon Burger"></food>
<food name="Whooper"></food>
</div>
<hr>
<h1>Log:</h1>
<ul>
<li v-for="vote in votes.log"> {{ vote }} </li>
</ul>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment