vue實現一個簡單的篩選及排序
阿新 • • 發佈:2018-12-04
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>newproject</title> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="searchName" /> <ul> <li v-for="(item,index) in filterPerson" :key="index"> {{index}}--{{item.name}}--{{item.age}} </li> </ul> <button @click="ageListChange(1)">按年齡升序排列</button> <button @click="ageListChange(2)">按年齡降序排列</button> <button @click="ageListChange(0)">按原來排列</button> </div> <script> new Vue({ el: '#app', data: { searchName: '', ageList: 0, //1-->升序,2-->降序 personList: [ {name: 'anna', age: 16}, {name: 'jack', age: 20}, {name: 'tom', age: 17}, {name: 'bobo', age: 18} ] }, computed: { filterPerson() { const {searchName,personList,ageList} = this; let fpList; fpList = personList.filter(item => { return item.name.indexOf(searchName)!==-1; }); if(ageList!==0) { fpList.sort(function(a1,a2){//正數,a1.age大,負數,a2.age大 if(ageList==1) { return a1.age-a2.age; }else{ return a2.age - a1.age; } }); } return fpList; } }, methods: { ageListChange(ageList) { this.ageList = ageList; } } }); </script> </body> </html>