<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, index) in candidates" :key="index" class="list-group-item">
{{candidate.name}} {{candidate.votes}}
<!-- increase votes 'on:click'-->
<button class="btn btn-default" @click="candidate.votes++">Vote</button>
</li>
</ul>
<!-- display the name of the 'mayor' using a computed property-->
<h2>Our mayor is {{mayor.name}}!</h2>
</div>
Vue
var vm = new Vue({
el: '.container',
data: {
candidates: [
{name: "Violet", votes: 0},
{name: "Dash", votes: 0},
{name: "Jack Jack", votes: 0},
{name: "Elastigirl", votes: 0},
{name: "Mr. Incredible", votes: 0},
]
},
computed: {
mayor: function () {
//first we sort the array descending
var candidatesSorted = this.candidates.sort(function (a, b) {
return b.votes - a.votes;
});
//the mayor will be the first item
return candidatesSorted[0];
}
},
methods: {
//this method runs when the key 'delete' is pressed
clear: function () {
console.log('clear')
//Turn votes of all candidate to 0 using map() function.
this.candidates = this.candidates.map(function (candidate) {
candidate.votes = 0;
return candidate;
})
}
}
})
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.