Vue 列表排序
阿新 • • 發佈:2022-04-12
具體實現
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>列表排序</title> <script type="text/javascript" src="../js/vue.js"></script> </head> <body> <div id="root"> <input type="text" placeholder="請輸入名字" v-model="keyWord"> <button @click="sortType = 2">升序</button> <button @click="sortType = 1">降序</button> <button @click="sortType = 0">預設</button> <ul> <li v-for="(p,index) in filPersons" :key="p.id"> {{p.name}} - {{p.sex}} - {{p.age}} </li> </ul> </div> </body> <script type="text/javascript"> new Vue({ el: '#root', data: { persons: [ {id: '001', name: '王大錘', sex: '女', age: 36}, {id: '002', name: '王小李', sex: '男', age: 19}, {id: '003', name: '李大剛', sex: '男', age: 21}, {id: '004', name: '王小剛', sex: '女', age: 20}, ], keyWord: '', sortType: 0 }, computed: { filPersons() { const arr = this.persons.filter((p) => { return p.name.indexOf(this.keyWord) !== -1 }) if (this.sortType) { arr.sort((p1, p2) => { return this.sortType === 1 ? p2.age - p1.age : p1.age - p2.age }) } return arr } } }) </script> </html>
程式碼分析
首先確定使用者的點選事件:設定 sortType:0
(0:預設、1:升序、2:降序)
sortType: 0
根據 sortType
:0 的值決定 升序 或 降序
if (this.sortType) {
arr.sort((p1, p2) => {
return this.sortType === 1 ? p2.age - p1.age : p1.age - p2.age
})
}