目录
前言
在前一个章节的基础上,如果我们还想加一个排序的过程应该如何修改呢?
要求:
1. 添加升序,降序,原顺序按钮进行列表排序
2. 过滤和排序可以结合使用
HTML文本
可以添加三个按钮,用v-on指令结合js表达式去分别标识升序,降序,原顺序,如0,1,2。代码如下。
<button v-on:click="sortType=2">年龄升序</button>
<button v-on:click="sortType=1">年龄降序</button>
<button v-on:click="sortType=0">原顺序</button>
Vue Script脚本
在原来的computed的filPersons中除了过滤人名以外,在对sortType进行判断,0的时候不去做修改,1时降序,2时升序。
computed: {
filPersons() {
// 计算属性规定,需要返回知道是什么值
const arr = this.personArr.filter((p) => {
//过滤语法规定,需要return返回值
return p.name.indexOf(this.nameKeyWord) !== -1
})
//判断是否需要排序, 当sortType有值时
if(this.sortType){
// 拿到过滤后的数组在排序
arr.sort((p1, p2)=>{
return this.sortType ===1?p2.age - p1.age : p1.age - p2.age
})
}
return arr
}
}
演示效果
过滤+ 排序效果如下
全部代码
<!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">
<!-- 遍历数组, 用的最多-->
<h2>人员列表</h2>
<!-- <button v-on:click.once="addPerson">添加人员</button> -->
<input type="text" placeholder="请输入名字" v-model="nameKeyWord">
<button v-on:click="sortType=2">年龄升序</button>
<button v-on:click="sortType=1">年龄降序</button>
<button v-on:click="sortType=0">原顺序</button>
<ul>
<!-- index是遍历时候的索引值,小括号可以不写,写了更加安全,不会引发不必要的问题 -->
<li v-for="(p, index) in filPersons" :key="p.id">{
{p.name}} - {
{p.age}} - {
{p.sex}}</li>
</ul>
</div>
</body>
<script>
Vue.config.productionTip = false // 阻止vue在启动时生成生产提示
new Vue({
el: '#root',
data: {
personArr: [
{ id: "001", name: '张译', age: 45, sex: '男' },
{ id: "002", name: '张颂文', age: 43, sex: '男' },
{ id: "003", name: '肖战', age: 18, sex: '男' },
{ id: "004", name: '赵丽颖', age: 21, sex: '女' },
],
nameKeyWord: '',
sortType: 0 // 0 原顺序,1 降序, 2 升序
},
computed: {
filPersons() {
// 计算属性规定,需要返回知道是什么值
const arr = this.personArr.filter((p) => {
//过滤语法规定,需要return返回值
return p.name.indexOf(this.nameKeyWord) !== -1
})
//判断是否需要排序, 当sortType有值时
if(this.sortType){
// 拿到过滤后的数组在排序
arr.sort((p1, p2)=>{
return this.sortType ===1?p2.age - p1.age : p1.age - p2.age
})
}
return arr
}
}
})
</script>
</html>