1. 程式人生 > 實用技巧 >vue 列表過濾排序

vue 列表過濾排序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="demo">
    <input type="text" v-model="searName">
    <input type="text" v-model="searAge">
    <ul>
        <li 
v-for="(p,index) in filePersons" :key="index"> {{p.name}}-------{{p.age}} </li> </ul> <button @click="setOrderType(1)">升序</button> <button @click="setOrderType(2)">降序</button> <button @click="setOrderType(0)">原序</button>
</div> <script type="text/javascript" src="vue.js"></script> <script type="text/javascript"> var vm = new Vue({ el: "#demo", data: { searName: '', searAge:'', orderType: 0, persons: [ {name: 'zhang
', age: '20'}, {name: 'li', age: '18'}, {name: 'wang', age: '20'}, {name: 'wu', age: '14'}, {name: 'yuan', age: '22'}, ] }, methods: { setOrderType(orderType) { this.orderType = orderType; } }, computed: { filePersons() { const {persons, orderType, searName, searAge} = this; let fper = persons.filter(p => { let filName = true; let filAge = true; if (searName) { filName = p.name.indexOf(searName) !== -1 } if (searAge) { filAge = p.age.indexOf(searAge) !== -1 } return filName && filAge; }) if (orderType !== 0) { fper.sort(function (p1, p2) { if (orderType == 1) { return p1.age - p2.age; } else { return p2.age - p1.age; } }) } return fper; } } }) </script> </body> </html>