14.列表排序.html 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <div id="app">
  10. 关键字搜索:
  11. <input type="text" placeholder="请输入关键字" v-model="keywords" />
  12. <br />
  13. <div id="main" v-for="(item,index) in newList" :key="index">
  14. {{index + 1}}.我叫{{item.name}}--今年{{item.age}}了--我是{{item.sex}}孩
  15. </div>
  16. <!-- @click 点击事件 -->
  17. <button @click="sortType = 1">升序</button>
  18. <button @click="sortType = 2">降序</button>
  19. <button @click="sortType = 0">默认顺序</button>
  20. </div>
  21. <script src="./vue.js"></script>
  22. <script>
  23. var app = new Vue({
  24. data: {
  25. arr: [
  26. {
  27. name: "Lucy",
  28. age: 11,
  29. sex: "女",
  30. },
  31. {
  32. name: "LiLi",
  33. age: 31,
  34. sex: "男",
  35. },
  36. {
  37. name: "八戒",
  38. age: 21,
  39. sex: "男",
  40. },
  41. {
  42. name: "八卦",
  43. age: 23,
  44. sex: "男",
  45. },
  46. {
  47. name: "孙悟空",
  48. age: 27,
  49. sex: "男",
  50. },
  51. {
  52. name: "唐僧",
  53. age: 33,
  54. sex: "女",
  55. },
  56. ],
  57. keywords: "",
  58. person: [],
  59. sortType: 0
  60. },
  61. computed:{
  62. newList() {
  63. this.person = this.arr.filter((item) => {
  64. return item.name.indexOf(this.keywords) !== -1
  65. })
  66. /**
  67. * 升序 降序
  68. * sort
  69. */
  70. if(this.sortType) {
  71. // 排序
  72. this.person.sort((a,b)=>{
  73. // if(this.sortType === 1) {
  74. // console.log("111")
  75. // return b.age - a.age;
  76. // } else if(this.sortType === 2) {
  77. // console.log("222")
  78. // return (a.age - b.age);
  79. // }
  80. // vue2.0框架 数据变化 视图未更新 ? 需要通过数据劫持去解决
  81. return this.sortType === 1 ? b.age - a.age : a.age - b.age;
  82. })
  83. }
  84. console.log(this.person,'333')
  85. return this.person;
  86. }
  87. },
  88. methods: {
  89. upSort() {
  90. console.log(this.person,'3333')
  91. this.person = this.person.sort((a,b) => {
  92. return a.age - b.age;
  93. })
  94. }
  95. },
  96. }).$mount("#app");
  97. </script>
  98. </body>
  99. </html>