Skip to content

Instantly share code, notes, and snippets.

@allysonsilva
Created December 2, 2017 14:19
Show Gist options
  • Save allysonsilva/6923541bf8270091dd089321eb030863 to your computer and use it in GitHub Desktop.
Save allysonsilva/6923541bf8270091dd089321eb030863 to your computer and use it in GitHub Desktop.
Vue.js ⚡️ Example - Events
Vue.component('chariot', {
props: ['chariot', 'current'],
template: "#chariot-template",
methods: {
rideChariot: function(chariot) {
this.$emit('select', chariot)
},
},
computed: {
//is true when the chariot has more horses than the current one
hasMoreHorses: function() {
return this.current.horses < this.chariot.horses
},
//is true when the chariot is the current one
isCurrent: function() {
return this.current.name == this.chariot.name
},
//is true when there is no chariot current
noChariot: function() {
return this.current.name == null;
},
//define the action for each chariot
action: function() {
if (this.noChariot) {
action = 'Pick Chariot'
} else if (this.isCurrent) {
action = 'Riding!'
} else if (this.hasMoreHorses) {
action = 'Hire Horses'
} else {
action = 'Dismiss Horses'
}
return action;
}
}
});
new Vue({
el: '#app',
data: {
chariots: [{
name: "Olympus",
horses: 4
},
{
name: "Sagitta",
horses: 3
},
{
name: "Icarus",
horses: 2
},
{
name: "Abraxas",
horses: 1
},
],
//the current 'chariot'
current: {}
},
methods: {
updateChariot: function(chariot) {
this.current = chariot
}
}
});
<div id="app">
<h1>Chariot shopping</h1>
<ul>
<chariot v-for="chariot in chariots" :chariot="chariot" :current="current" @select="updateChariot"></chariot>
</ul>
<pre>{{ $data }}</pre>
</div>
<template id="chariot-template">
<li>
<h4>"{{ chariot.name }}" chariot has <strong>{{ chariot.horses }}</strong> horse(s)!</h4>
<button @click="rideChariot(chariot)" :disabled="isCurrent">
{{ action }}
</button>
</li>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment