将搜索的结果进行排序
降序
升序
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="root">
<h1>人员列表</h1>
<!-- 模糊搜索 -->
<input type="text" placeholder="请输入名字" v-model="keyword">
<!-- 用2代表 -->
<button v-on:click="sortType=2">年龄升序</button>
<!-- 用1代表 -->
<button v-on:click="sortType=1">年龄降序</button>
<!-- 用0代表 -->
<button v-on:click="sortType=0">原顺序</button>
<ul>
<li v-for="(item,index) in odel">
{{item .id}}--{{item.name}}--{{item.age}}
</li>
</ul>
</div>
<script>
var vm = new Vue({
el: '#root',
data: {
start: [{
id: 001,
name: '马冬梅',
age: 20
}, {
id: 002,
name: '周冬雨',
age: 30
}, {
id: 003,
name: '周杰伦',
age: 40
}, {
id: 004,
name: '温兆伦',
age: 50
}],
keyword: '',
sortType: 0, //0原顺序,1降序 2升序
},
// 计算属性刚开始就会调用一次
computed: {
odel() {
// 计算属性的return
const arr = this.odel = this.start.filter((item) => {
// 这个return 是filter的
return item.name.indexOf(this.keyword) !== -1
})
// 判断一下是否升序
if (this.sortType === 1 || this.sortType === 2) {
// sort排序
arr.sort((a, b) => {
return this.sortType === 1 ? b.age - a.age : a.age - b.age
})
}
return arr
}
}
})
// sort排序的使用
let aa = [1, 45, 67]
aa.sort((a, b) => {
// a-b升序 b-a降序
return b - a
})
console.log(aa)
</script>
</body>
</html>