VUE实例课程---1、计算属性实现列表的搜索和排序
一、总结
一句话总结:
计算属性实现列表的搜索和排序中:计算属性用于搜索的关键字变化之后自动更新列表数组,排序就是指定不同的排序标志,根据不同的排序字段来改变列表元素的顺序
<div id="app"> <label> 搜索名字:<input type="text" v-model="searchName"> </label> <p v-for="item in filterPersons"> {{item.id}}---{{item.name}}---{{item.age}} </p> <div> <button @click="setOrderType(1)">年龄升序</button> <button @click="setOrderType(-1)">年龄降序</button> <button @click="setOrderType(0)">原本顺序</button> </div> </div> <script src="../js/vue.js"></script> <script> let vm = new Vue({ el: '#app', data: { searchName:'', orderType: 0, // 0代表不排序, 1代表升序, -1代表降序 persons: [ {id:1,name:'刘备',age:23}, {id:2,name:'张飞',age:22}, {id:3,name:'关羽',age:41}, {id:4,name:'赵云',age:33}, {id:5,name:'赵羽飞',age:15}, {id:6,name:'刘禅',age:13}, {id:7,name:'刘云禅',age:2} ] }, computed:{ filterPersons:function () { // 取出相关数据 const {searchName, persons, orderType} = this; let arr=[...persons];//初始值 // 过滤数组 if(searchName.trim()){ arr=persons.filter(p=>p.name.indexOf(searchName)!==-1); } //排序 if(orderType){ arr.sort(function (a,b) { if(orderType===1){ return a.age-b.age; }else{ return b.age-a.age; } }); } return arr; } }, methods:{ setOrderType(orderType){ this.orderType=orderType; } } }); </script>
二、计算属性实现列表的搜索和排序
博客对应课程的视频位置:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>1、计算属性实现列表的搜索和排序</title> 6 </head> 7 <body> 8 <!-- 9 10 计算属性实现列表的搜索和排序中: 11 计算属性用于搜索的关键字变化之后自动更新列表数组, 12 排序就是指定不同的排序标志,根据不同的排序字段来改变列表元素的顺序 13 14 --> 15 <div id="app"> 16 <label> 17 搜索名字:<input type="text" v-model="searchName"> 18 </label> 19 <p v-for="item in filterPersons"> 20 {{item.id}}---{{item.name}}---{{item.age}} 21 </p> 22 <div> 23 <button @click="setOrderType(1)">年龄升序</button> 24 <button @click="setOrderType(-1)">年龄降序</button> 25 <button @click="setOrderType(0)">原本顺序</button> 26 </div> 27 28 </div> 29 <script src="../js/vue.js"></script> 30 <script> 31 let vm = new Vue({ 32 el: '#app', 33 data: { 34 searchName:'', 35 orderType: 0, // 0代表不排序, 1代表升序, -1代表降序 36 persons: [ 37 {id:1,name:'刘备',age:23}, 38 {id:2,name:'张飞',age:22}, 39 {id:3,name:'关羽',age:41}, 40 {id:4,name:'赵云',age:33}, 41 {id:5,name:'赵羽飞',age:15}, 42 {id:6,name:'刘禅',age:13}, 43 {id:7,name:'刘云禅',age:2} 44 ] 45 }, 46 computed:{ 47 filterPersons:function () { 48 // 取出相关数据 49 const {searchName, persons, orderType} = this; 50 let arr=[...persons];//初始值 51 52 // 过滤数组 53 if(searchName.trim()){ 54 arr=persons.filter(p=>p.name.indexOf(searchName)!==-1); 55 } 56 57 //排序 58 if(orderType){ 59 arr.sort(function (a,b) { 60 if(orderType===1){ 61 return a.age-b.age; 62 }else{ 63 return b.age-a.age; 64 } 65 }); 66 } 67 return arr; 68 } 69 }, 70 methods:{ 71 setOrderType(orderType){ 72 this.orderType=orderType; 73 } 74 } 75 }); 76 </script> 77 </body> 78 </html>