vuejs2 - 在 Vue.js 中对数组进行排序

标签 vuejs2

在 v-for 循环中显示数组之前,如何按名称或性别对数组进行排序?
https://jsfiddle.net/rg50h7hx/

<div id="string">
  <ul>
    <li v-for="array in arrays">{{ array.name }}</li>
  </ul>
</div>

// Vue.js v. 2.1.8
var string = new Vue({
  el: '#string',
  data: {
    arrays: [
      { name: 'kano',    sex: 'man' },
      { name: 'striker', sex: 'man' },
      { name: 'sonya',   sex: 'woman' },
      { name: 'sindell', sex: 'woman' },
      { name: 'subzero', sex: 'man' }
    ]
  }
})

我必须使用“计算”​​还是其他什么?

最佳答案

是的,一个简单的方法是创建一个可以返回 sortedArray 的计算属性,如下所示:

computed: {
  sortedArray: function() {
    function compare(a, b) {
      if (a.name < b.name)
        return -1;
      if (a.name > b.name)
        return 1;
      return 0;
    }

    return this.arrays.sort(compare);
  }
}

见工作demo .

您可以找到排序文档 here它需要一个 compareFunction。

compareFunction Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

关于vuejs2 - 在 Vue.js 中对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42883835/

相关文章:

javascript - 删除对象属性 (VueJs)

javascript - Vue js将多个选择框值(数组)发送到文本区域并附加该值

javascript - Vue.js 无法在方法中遍历对象

javascript - 将自定义数据传递给 vue-router 中的 `$router.push()`

javascript - 使用 Vue.js 更改 CSS 类属性

javascript - Vue js - 将 Prop 定义为特定类型

node.js - 如何容器化 Vue.js 应用程序?

typescript Vue : using a dynamic string name for a method

vue.js - 当我使用相同的用户名时,如何不使用 :key=”$route. 路径”

javascript - BootstrapVue 访问 slot 模板中的 b-table 行数据