我现在正在锻炼,我想根据猫的照片投票数对我的数据进行排序。我想按“更多投票”排序为“很少投票”,并尽可能保存数据,以便在刷新时仍对表进行排序。我开始编写一些代码,但是似乎没有用。
HTML代码:
<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: {{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>
<br>
<button v-on:click="sortBy(counter)">Sort</button>
<p id="demo"></p>
</th>
</tr>
</table>
</div>
</div>
和JS代码:
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;
},
},
})
因此,我找到了一个代码,开发人员在其中使用sortKey(这是排序的参数),因此我的参数显然是计数器,我尽力编写代码,以便通过减少计数器进行排序。但它不起作用。 任何帮助将不胜感激。 谢谢你们
答案 0 :(得分:0)
您可以使用Array
方法对array.sort()
进行排序。 array.sort()
方法的用法:
let values = [45, 213, 234, 6, 5, 5464, 54,6];
values.sort((a, b) => a - b); // This will sort lower value to higher value
values.sort((a, b) => b - a); // This will sort higher value to lower value
关于您的数据:
let 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
}
];
gridData.sort((a, b) => a.counter - b.counter); // This will sort your gridData array by counter, lower values to higher values
gridData.sort((a, b) => b.counter - a.counter); // This will sort your gridData array by counter, lower valeus to higher values