lundi 31 décembre 2018

How to sort data and save it in VueJS

I'm doing an exercise right now and I would like to sort my data according to the number of vote of an image of cat. I want to sort by "more vote" to "few vote" and if possibly, save the data so when I refresh, the table is still sorted. I started to code a little bit but it doesn't seems to work.

HTML code :

    <div id="display" class="container">
    <table class="w3-striped w3-table-all table table-bordered" id="tableDisplay">
      <tr class="w3-hover-light-grey">
        <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>
            <br>
            <button v-on:click="sortBy(counter)">Sort</button>
            <p id="demo"></p>
          </th>
        </tr>
      </table>

    </div>

  </div>

and the JS code :


  new Vue({
  el: '#display',
  data: {
    sortKey: 'counter',

    gridData: [
      {
        "url": "http://24.media.tumblr.com/tumblr_m82woaL5AD1rro1o5o1_1280.jpg",
        "id": "MTgwODA3MA",
        "counter": 3
      },
      {
        "url": "http://24.media.tumblr.com/tumblr_m29a9d62C81r2rj8po1_500.jpg",
        "id": "tt",
        "counter": 5
      }
    ],
  },

  methods: {
    test: function(idx) {
      localStorage.getItem(gridData);
      this.gridData[idx].counter++;
      this.gridData.saveCounter(this.gridData[idx].counter++, idx);
    },
    saveCounter :function(param,idx){
      localStorage.setItem('gridData[idx].counter', param);
    },
    deleteItem: function(idx) {
      this.gridData.splice(idx,1);
    },
    sortBy: function(sortKey) {
      this.reverse = (this.sortKey == sortKey) ? ! this.reverse : false;
      this.sortKey = sortKey;
    },

  },
})

So I find a code where the developer use sortKey which is the parameters of sorting, so my parameters is obviously the counter and I tried my best to code so it sort by decreasing counter. But it doesnt work. Any help would be appreciate. Thank you guys




Aucun commentaire:

Enregistrer un commentaire