zoukankan      html  css  js  c++  java
  • (尚010)Vue列表的搜素和排序

     1.test010.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <!--
    1.列表过滤
    2.列表排序
    -->
    <div id="test">
    <input type="text" v-model="searchName">
    <ul>
    <!--filterPersons应该为persons过滤后产生的结果-->
    <li v-for="(p,index) in filterPersons" :key="index">
    {{index}}--{{p.name}}---{{p.age}}
    </li>
    </ul>

    <!--需要怎样排序,需要给orderType设置值-->
    <button @click="setOrderType(1)">年龄升序</button>
    <button @click="setOrderType(2)">年龄降序</button>
    <button @click="setOrderType(0)">原本顺序</button>
    </div>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript">
    new Vue({
    el:'#test',
    data:{
    searchName:'',
    orderType:0,//自己设计:0代表原本顺序,1代表升序排序,2代表降序排序
    //数组
    persons:[
    {name:'赵云',age:'18'},
    {name:'张飞',age:'16'},
    {name:'关羽',age:'21'},
    {name:'刘备',age:'2'}
    ],
    },
    computed:{
    //搜索过滤
    filterPersons(){
    //取出相关数据,并进行结构赋值
    const {searchName,persons,orderType}=this
    //定义最终返回数组(最终需要显示的数组)
    let fPersons;

    //对persons进行过滤
    //需要看p.name中是否包含searchName,调用这个方法p.name.indexOf(searchName):indexOf为看字符串searchName在当前字符串p.name的下标
    //一旦不等于-1,说明包含了
    fPersons=persons.filter(p=>p.name.indexOf(searchName)!==-1);
    //排序
    if(orderType!==0){
    //排序调用sort()方法,还需要传比较函数
    fPersons.sort(function(p1,p2){//如果返回的是负数,p1在前;返回正数p2在前
    //1代表升序排序,2代表降序排序
    if(orderType===2){
    return p2.age-p1.age;
    }else{
    return p1.age-p2.age;
    }
    })
    }
    return fPersons;
    }
    },

    methods:{
    setOrderType(orderType){
    this.orderType=orderType
    }
    }
    })
    </script>
    </body>
    </html>

  • 相关阅读:
    js数据类型转换
    html5的onhashchange和history历史管理
    Javascript语言精粹-毒瘤和糟粕
    [夏天Object]运行时程序执行的上下文堆栈(一)
    [Object]继承(经典版)(五)封装
    [Object]继承(经典版)(四)多重继承和组合继承
    flex 弹性布局的大坑!!
    带视觉差的轮播图
    不用循环的数组求和
    CSS3盒模型display:box简述
  • 原文地址:https://www.cnblogs.com/curedfisher/p/12017472.html
Copyright © 2011-2022 走看看