<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--列表过滤与排序--> <div id="demo"> <input type="text" v-model="searchName"> <ul> <li v-for="(p,index) in filterPersons" :key="index"> {{index}}----{{p.name}}----{{p.age}} </li> </ul> <br/> <button @click="setOrderType(1)">年龄升序</button> <button @click="setOrderType(2)">年龄降序</button> <button @click="setOrderType(0)">原本顺序</button> </div> <script type="text/javascript" src="lib/vue.min.js"></script> <script> new Vue({ el: "#demo", data: { orderType: 0, //0原本排序, 1:升序, 2:降序 searchName: '', persons: [ // vue只是监视了persons的改变, 没有监视persons内部数组的改变 {name: 'Tom', age: 12}, {name: 'Admin', age: 13}, {name: 'Root', age: 16}, {name: 'Rose', age: 10}, ] }, // 计算属性在初始化时会调用,在相关的属性发生变化时会调用 computed: { filterPersons(){ // 取出相关的数据 const {searchName, persons, orderType} = this; //最终要显示的数据 let fPersons; // 对persons进行过滤 fPersons = persons.filter(p => p.name.indexOf(searchName) !== -1); //排序 if (orderType !== 0) { fPersons.sort(function (p1, p2) { // 1:升序, 2:降序 if (orderType === 2) { return p2.age - p1.age } return p1.age - p2.age }) } return fPersons; } }, methods: { setOrderType(num){ this.orderType = num; } } }); </script> </body> </html>
vue的计算属性很重要....