vue列表筛选+排序笔记
vue列表筛选+排序笔记
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>vue列表筛选+排序</title> </head> <body> <div id="app"> <input type="text" v-model="keyword"> <ul> <li v-for="(val,index) in filterLists" :key="index">{{index}}-{{val.id}}-{{val.name}}-{{val.age}}</li> </ul> <button @click="ageOrderBy(1)">年龄升序</button> <button @click="ageOrderBy(2)">年龄降序</button> <button @click="ageOrderBy(0)">年龄原序</button> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> const vm = new Vue({ el: '#app', data: { keyword: '', orderBy: 0, //0原序,1升序,2降序 lists: [{ 'id': 0, 'name': '小红果', 'age': 25 }, { 'id': 1, 'name': '小青果', 'age': 15 }, { 'id': 6, 'name': '小青青', 'age': 11 }, { 'id': 10, 'name': '小青社', 'age': 11 }, { 'id': 2, 'name': '小绿果', 'age': 18 }, { 'id': 3, 'name': '小蓝果', 'age': 16 }, { 'id': 4, 'name': '小粉果', 'age': 17 }, ] }, computed: { //关键字筛选 filterLists() { const { keyword, lists, orderBy } = this; let filterL; //过滤 filterL = lists.filter(function(val) { return val.name.indexOf(keyword) > -1 }); if (orderBy > 0) { //排序 升序 if (orderBy === 1) { filterL.sort(function(val1, val2) { return val1.age - val2.age }) } else { //排序 降序 filterL.sort(function(val1, val2) { return val2.age - val1.age }) } } return filterL; } }, methods: { ageOrderBy(orderBy) { this.orderBy = orderBy } } }) </script> </body> </html>
Dcr163的博客
http://dcr163.cn/414.html(转载时请注明本文出处及文章链接)