jeudi 20 décembre 2018

Saving data locally in VueJS

I need to implement a function that will vote for a specific picture every time we click on the “Vote” button. And more importantly, I need to store these “Vote” so when I refreshed the page it doesn’t reinitialize. Here is my code below :

    <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: </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>

and my Vue JS code :


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++;
      this.saveCounter(idx);
    },
    saveCounter :function(idx){
      let parsed = JSON.stringify(this.gridData[idx].counter);
      localStorage.setItem('this.gridData[idx].counter', parsed);
    },
  },
})

You can see that I use the function setItem to save in the gridData[id].counter but it doesn’t work.




Aucun commentaire:

Enregistrer un commentaire