[Vuejs]-How to implement multiple counter in VueJS

0👍

Change <div v-for="display in gridData"> to <div v-for="(display, idx) in gridData"> so that you know which item in the array you are using.

v-on:click="test(display.counter,display.id) to v-on:click="test(idx)

and the test function to:

test: function(idx) {
  this.gridData[idx].count++;
}

So that you are incrementing the count of the array item.

Currently you are just incrementing the argument count (an instance variable that dies after the scope of test ends) which does nothing.


See below:

new Vue({
  el: '#display',
  data: {
    gridData: [{
        "url": "http://24.media.tumblr.com/tumblr_m82woaL5AD1rro1o5o1_1280.jpg",
        "id": "MTgwODA3MA",
        "counter": 0
      },
      {
        "url": "http://24.media.tumblr.com/tumblr_m29a9d62C81r2rj8po1_500.jpg",
        "id": "tt",
        "counter": 0
      }
    ],
  },
  methods: {
    test: function(idx) {
      this.gridData[idx].counter++;
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="display" class="container">
  <table class="w3-table-all" id="tableDisplay">
    <tr>
      <th>Cat</th>
      <th>Vote</th>
    </tr>
  </table>
  <div v-for="(display,idx) in gridData">
    <table class="w3-striped w3-table-all table table-bordered" id="tableDisplay">
      <tr class="w3-hover-light-grey">
        <th>
          <img :src="display.url" height="200px" width="300px" />
        </th>
        <th>
          <div>Current Votes: {{display.counter}}</div>
          <button class="w3-button w3-green w3-hover-light-green" v-on:click="test(idx)" v-bind:id="display.id">Vote !</button>
        </th>
      </tr>
    </table>

  </div>

</div>

0👍

Repeated elements with functionality like this is where components are really handy. Break the individual item display into its own sub-component, like this:

<div v-for="display in gridData">
    <vote-widget :picture="display"></vote-widget>
</div>

Each one will have its own data and isolated scope.

Leave a comment