Skip to content

Instantly share code, notes, and snippets.

@allysonsilva
Last active December 2, 2017 14:20
Show Gist options
  • Save allysonsilva/4dc566f48a461530c02df85577fe3420 to your computer and use it in GitHub Desktop.
Save allysonsilva/4dc566f48a461530c02df85577fe3420 to your computer and use it in GitHub Desktop.
Vue.js ⚡️ Example - Events
Vue.component('story', {
template: "#story-template",
props: ['story', 'favorite'],
methods: {
upvote: function() {
this.story.upvotes += 1;
this.story.voted = true;
},
markAsFavorite: function() {
// 'update' is just the name of the custom event
// it could be anything. ex: fav-update
this.$emit('update', this.story)
},
},
computed: {
isFavorite: function() {
return this.story == this.favorite;
},
}
});
new Vue({
el: '#app',
data: {
stories: [{
plot: 'My horse is amazing.',
writer: 'Mr. Weebl',
upvotes: 28,
voted: false,
},
{
plot: 'Narwhals invented Shish Kebab.',
writer: 'Mr. Weebl',
upvotes: 8,
voted: false,
},
{
plot: 'The dark side of the Force is stronger.',
writer: 'Darth Vader',
upvotes: 49,
voted: false,
},
{
plot: 'One does not simply walk into Mordor',
writer: 'Boromir',
upvotes: 74,
voted: false,
},
],
favorite: {}
},
methods: {
updateFavorite: function(story) {
this.favorite = story;
},
},
});
<div id="app">
<h1>Let's hear some stories!</h1>
<ul>
<story v-for="story in stories" :story="story" :favorite="favorite" @update="updateFavorite"></story>
</ul>
<pre>
{{ $data }}
</pre>
</div>
<template id="story-template">
<li>
{{ story.writer }} said "{{ story.plot }}". Story upvotes {{ story.upvotes }}.
<button v-show="!story.voted" @click="upvote"> Upvote </button>
<button v-show="!isFavorite" @click="markAsFavorite"> Favorite </button>
<span v-show="isFavorite" class="glyphicon glyphicon-star pull-right" aria-hidden="true">✅</span>
</li>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment