Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

vuejs2 - Sort an array in Vue.js

How can I sort an array by name or sex before displaying it in a v-for loop? 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' }
    ]
  }
})

Do I have to use a "computed", or whatever?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, an easy way to do this can be create a computed property which can return the sortedArray, like following:

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);
  }
}

See working demo.

You can find the documentation of sort here which takes a 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...