Last active
December 2, 2017 14:20
-
-
Save allysonsilva/4dc566f48a461530c02df85577fe3420 to your computer and use it in GitHub Desktop.
Vue.js ⚡️ Example - Events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}, | |
}, | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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