标签:let zhang 排序 指定 xiaomi model ext 方法 indexof
1、案例1
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>列表的搜索和排序</title> </head> <!-- 1、根据输入框中输入的条件对数组进行过滤 2、对过滤后的结果按照指定顺序排序 --> <body> <div id="app"> <input type="text" v-model="searchName" /> <ul> <li v-for="(item,index) in filterPersons"> {{index}} --- {{item.name}} --- {{item.age}} </li> </ul> <button @click="clickFunc(1)">年龄升序</button> <button @click="clickFunc(2)">年龄降序</button> <button @click="clickFunc(0)">原本顺序</button> <button @click="clickFunc2">改变persons</button> </div> <script src="../js/vue.js" type="text/javascript"></script> <script> const vm = new Vue({ el: "#app", data: { orderType: 0, //默认是原本顺序 searchName: "", persons: [ { name: "liuyang", age: 28 }, { name: "yangjing", age: 19 }, { name: "zhangsan", age: 25 }, { name: "xiaoming", age: 30 }, ] }, methods: { clickFunc(param) { this.orderType = param; }, clickFunc2() { //同样会触发filterPersons()方法重新计算filterPersons的值 this.persons.splice(0, 1); } }, computed: { /* filterPersons是根据orderType、searchName、persons 三个相关数据计算而来的,只要这三个有改变就会重新计算filterPersons 的值 */ filterPersons() { /* 等效于: const orderType = this.orderType; const searchName = this.searchName; const persons = this.persons; */ const { orderType, searchName, persons } = this; //p是persons的每个元素 //返回true就是过滤后我们需要的数据 let results = persons.filter(p => p.name.indexOf(searchName) !== -1); results.sort(function (a, b) { if (orderType === 1) { //升序 return a.age - b.age } else if (orderType === 2) { //降序 return b.age - a.age } }); return results; } } }); </script> </body> </html>
标签:let zhang 排序 指定 xiaomi model ext 方法 indexof
原文地址:https://www.cnblogs.com/liuyang-520/p/12458466.html