4.列表排序.html 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>列表排序</title>
  8. <!-- 引入vue -->
  9. <script type="text/javascript" src="../js/vue.js"></script>
  10. </head>
  11. <body>
  12. <!-- 准备好一个容器 -->
  13. <div id="root">
  14. <h2>人员列表</h2>
  15. <input type="text" placeholder="请输入名字" v-model="keyWord"></input>
  16. <button @click="sortType=2">年龄升序</button>
  17. <button @click="sortType=1">年龄降序</button>
  18. <button @click="sortType=0">原顺序</button>
  19. <ul>
  20. <li v-for="(p,index) in filPersons" :key="p.id">
  21. {{p.name}}-{{p.age}}-{{p.sex}}
  22. </li>
  23. </ul>
  24. </div>
  25. </body>
  26. <script type="text/javascript">
  27. Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示
  28. new Vue({
  29. el: '#root',
  30. data: {
  31. keyWord: '',
  32. sortType:0, //0代表原顺序 1代表降序 2代表升序
  33. persons: [
  34. { id: '001', name: '马冬梅', age: 30, sex: '女' },
  35. { id: '002', name: '周冬雨', age: 31, sex: '女' },
  36. { id: '003', name: '周杰伦', age: 18, sex: '男' },
  37. { id: '003', name: '温兆伦', age: 19, sex: '男' }
  38. ]
  39. },
  40. computed: {
  41. filPersons() {
  42. const arr = this.persons.filter((p) => { //这里的return是计算属性规定的,要返回一个值
  43. return p.name.indexOf(this.keyWord) !== -1 //这里的return是filter规定的,要返回一个过滤的条件
  44. })
  45. //判断一下是否需要排序
  46. if(this.sortType){
  47. arr.sort((p1,p2)=>{
  48. return this.sortType === 1 ? p2.age-p1.age : p1.age-p2.age
  49. })
  50. }
  51. return arr
  52. }
  53. }
  54. })
  55. </script>
  56. </html>