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, 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;
      })
    }
  }
})