I recently came across a tutorial on voting for a Mayoral Candidate. The tutorial includes a sort function that determines the winner based on votes. However, I noticed that the sort function also rearranges the candidate list in real time, which is not ideal as it causes the Candidate Name and Vote buttons to shift their positions. My preference is to have the sort function only affect the result and not alter the layout of the page.
HTML
<div class="container">
<div id="mayor-vote">
<h2>Mayor Vote</h2>
<ul class="list-group" style="width: 400px;">
<li v-for="candidate in candidates" class="list-group-item clearfix">
<div class="pull-left">
<strong style="display: inline-block; width: 100px;">{{ candidate.name }}:</strong> {{ candidate.votes }}
</div>
<button class="btn btn-sm btn-primary pull-right" @click="candidate.votes++">Vote</button>
</li>
</ul>
<h2>Our Mayor is <span class="the-winner" :class="textClass">{{ mayor.name }}</span></h2>
<button @click="clear" class="btn btn-default">Reset Votes</button>
<br><br>
<pre>
{{ $data }}
</pre>
</div>
</div>
JS - refer to computed property
new Vue({
el: '#mayor-vote',
data: {
candidates: [
{ name: "Mr. Black", votes: 140 },
{ name: "Mr. Red", votes: 135 },
{ name: "Mr. Pink", votes: 145 },
{ name: "Mr. Brown", votes: 140 }
]
},
computed: {
mayor: function(){
var candidateSorted = this.candidates.sort(function(a,b){
return b.votes - a.votes;
});
return candidateSorted[0];
},
textClass: function() {
return this.mayor.name.replace(/ /g,'').replace('Mr.','').toLowerCase();
}
},
methods: {
clear: function() {
this.candidates = this.candidates.map( function(candidate){
candidate.votes = 0;
return candidate;
})
}
}
});
Feel free to check out the working version here: https://jsfiddle.net/7dadjbzs/