如何在Vue中对具有2个字段的数组进行排序?

wob*_*ano 3 javascript arrays sorting vue.js computed-properties

所以我有这张桌子:

在此处输入图片说明

而且我使用了这个vue2过滤器库,我只能使用该按单个字段进行排序。

我想做的是使用scoreand time_consumed字段按降序对数组进行排序。分数越高,时间消耗的时间越短,位置越高。

在上面的示例中,顺序应类似于:

1. 12 | 10141
2. 5 | 15233
3. 5 | 16233
4. 3 | 11495
Run Code Online (Sandbox Code Playgroud)

我使用了库中的orderBy过滤器,但是我只能使用

v-for="u in orderBy(users, 'score', -1)"
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法可以做到这一点?任何帮助将非常感激。

Ber*_*ert 5

使用计算值对分数进行排序。

console.clear()

const scores = [
  {
    score: 3,
    time_consumed: 11495
  },
  {
    score: 5,
    time_consumed: 16233
  },
  {
    score: 5,
    time_consumed: 15233
  },
  {
    score: 12,
    time_consumed: 10141
  },
]

new Vue({
  el:"#app",
  data:{
    scores
  },
  computed:{
    sortedScores(){
      const sorter = (a,b) => b.score - a.score || a.time_consumed - b.time_consumed
    
      return this.scores.sort(sorter)
    }
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app">
  <table>
    <tr v-for="score in sortedScores">
      <td>{{score.score}}</td>
      <td>{{score.time_consumed}}</td>
    </tr>
  </table>
</div>
Run Code Online (Sandbox Code Playgroud)

排序器对两个值都起作用,因为如果分数相等,它将最终使用time_consumed。