vue案例:列表过滤+列表排序

在前端中,对列表进行操作时我们可以选择在保留原数据的情况下,对用户进行的操作进行过滤排序后存储到新的变量中,而后以遍历的方式展现出来。

案例:实现用户输入名字下面的数据进行显示,通过右侧升序降序原序按钮对数据的年龄进行排序
在这里插入图片描述

<!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">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>

<body>
    <div class="content">
        <h1>人员列表</h1>
        <!-- 通过v-model双向绑定keyworld,用户在输入框输入的值储存到keyword中 -->
        <input type="text" placeholder="请输入名字" v-model="keyword">
        <!-- 按下按钮,改变sortType的值 -->
        <input type="button" value="升序" @click="sortType=1">
        <input type="button" value="降序" @click="sortType=2">
        <input type="button" value="原序" @click="sortType=0">
        <ul>
            <!-- 在此处不改动原数据的情况下对过滤后的数组进行排序,所以此处是遍历filterperson而不是persons -->
            <li v-for="p in filterperson" :key="p.key">
                {
   
   {p.name}}-{
   
   {p.age}}-{
   
   {p.sex}}
            </li>
        </ul>
    </div>
    <script>
        const vm = new Vue({
      
      
            el: '.content',
            data: {
      
      
                sortType: '',   //储存按下按钮的情况,用于后面判断用户按下了哪个按钮
                keyword: '',    //双向绑定用户输入框中的内容
                persons: [      //原数据
                    {
      
       id: '001', name: '马冬梅', age: '25', sex: '女' },
                    {
      
       id: '002', name: '周冬雨', age: '20', sex: '女' },
                    {
      
       id: '003', name: '周杰伦', age: '18', sex: '男' },
                    {
      
       id: '004', name: '温兆伦', age: '22', sex: '男' },
                ]
            },
            computed: {
      
      
                filterperson() {
      
      
                //原数据进行过滤,此处注意过滤后的数据不会影响原数据,会生成新的数据。将新数据存储到searchPerson中
                    const searchPerson = this.persons.filter((p) => {
      
       
                    //检索name中含有输入框中输入的数据(-1表示没有找到指定内容),并将其返回,作为过滤后的数据      
                        return p.name.indexOf(this.keyword) !== -1;         
                    });
                    if (this.sortType) {
      
              //由上面按下的按钮可知,0为原序,1为升序,2为降序。当sortType为真(1,2)时,进行以下操作
                        searchPerson.sort((a, b) => {
      
         //对检索后的数据进行排列
                            return this.sortType === 1 ? a.age - b.age : b.age - a.age  //a-b为升序,b-a为降序,排序后的数据返回给searchPerson
                        })
                    };
                    return searchPerson;    //最后将检索和排序后的数据进行返回
                }
            }

        })
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/cy6661/article/details/129581735