vfor 发表于 2019-05-16 | 分类于 Vue | 评论数: 一个简单排序,注意这里面sort方法容易掉的坑,不仅是vue所有的js都有这个bug,因此这种解决方式很常用 123456789101112131415161718192021222324252627282930313233343536373839<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <title>Document</title></head><body><div id="app"> <ul> <li v-for="item in sortItems">{{item}}</li> //注意这里的sortItems别写成items了! </ul></div><script> new Vue({ el:"#app", data:{ items:[1,4,3,78,45] }, computed:{ sortItems://注意在vue中为了保护data这里必须重新命名不能用items function(){ return this.items.sort(sortNum) //若不再定义一个sortNum,将出现收字符排序完了再排下一个,如1,23,4,5,67 } } }); //注意这个函数写的位置,应写在vue后 function sortNum(a,b){ return a-b; }</script> </body></html> 结果: 对象数组排序 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <title>Document</title></head><body><div id="app"> <ul> <li v-for="(student,index) in sortStudents">{{index+1}}:{{student.name}}-{{student.age}}</li> <!-- 注意这里的索引的用法 --> </ul></div><script> new Vue({ el:"#app", data:{ students: [ {name:'linguoqiang',age:21}, {name:'liuxue',age:21}, {name:'chenhong',age:20}, {name:'chenqianqian',age:19}, {name:'guomengyu',age:18}, ] }, computed:{ sortStudents: //千万注意不要画蛇添足在这里加花括号,否则会出错 function(){ return sortByKey(this.students,'age') } } }); //对象数组排序方法,在网上搜直接拿过来用就好 function sortByKey(array,key){ return array.sort(function(a,b){ var x=a[key]; var y=b[key]; return ((x<y)?-1:((x>y)?1:0)); });} </script> </body></html> 结果: -------------本文结束感谢您的阅读-------------