Vue
by Alex Kyriakidis
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div class="container" @keydown.esc.prevent="clear">
<h1>Dog Elections</h1>
<ul class="list-group">
<li v-for="candidate in candidatesSorted" :key="candidate.name" class="list-group-item">
{{candidate.name}} {{candidate.votes}}
<!-- increase votes 'on:click'-->
<button class="btn btn-default" @click="vote(candidate)">Vote</button>
</li>
</ul>
<!-- display the name of the 'mayor' using a computed property-->
<h2>Our mayor is {{mayor.name}}!</h2>
<h3>Original Order</h3>
<ul class="list-group">
<li v-for="candidate in candidates" :key="candidate.name" class="list-group-item">
{{candidate.name}} {{candidate.votes}}
<!-- increase votes 'on:click'-->
<button class="btn btn-default" @click="vote(candidate)">Vote</button>
</li>
</ul>
</div>
Vue
var vm = new Vue({
el: '.container',
data: {
candidates: [
{name: "Mr. Black", votes: 0},
{name: "Mr. White", votes: 0},
{name: "Mr. Pink", votes: 0},
{name: "Mr. Brown", votes: 0}
]
},
computed: {
candidatesSorted () {
let candidatesSorted = [...this.candidates].sort((a, b) => b.votes - a.votes)
return candidatesSorted
},
mayor () {
return this.candidatesSorted[0]
}
},
methods: {
vote (candidate) {
candidate.votes++
},
clear () {
this.candidates = this.candidates.map(candidate => {
candidate.votes = 0
return candidate
})
}
}
})