vue.js学习笔记5--列表的搜索和排序

vue.js学习笔记5–列表的搜索和排序

  1. vue代码实现

    <template>
    	<div>
    		<input v-model="inputValue"/>
    		<ul>
    			<li v-for="(item,index) of filterPersons" :key="index">
    				{{index}}--{{item.name}}--{{item.age}}
    			</li>
    		</ul>
    		<button @click="setOrderType(1)">年龄升序</button>
    		<button @click="setOrderType(2)">年龄降序</button>
    		<button @click="setOrderType(0)">原本顺序</button>
    	</div>
    </template>
    
    <script>
    	export default {
    		data(){
    			return{
    				persons:[
    				{name:'Tom',age:18},
    				{name:'Jarry',age:19},
    				{name:'Bob',age:18},
    				{name:'Rose',age:17},
    				{name:'Cat',age:16},
    				{name:'Make',age:15},
    				{name:'Susan',age:14},
    				{name:'Lily',age:18}
    				],
    				inputValue:'',
    				orderType:0, //0代表原本顺序,1代表升序,2代表降序
    			}
    		},
    		computed:{
    			filterPersons(){
    				//取出相关的数据
    				const {inputValue,persons,orderType}=this   //
    				
    				//最终需要显示的数组
    				let fPersons;
    				//对persons进行过滤
    				fPersons=persons.filter(p=>p.name.indexOf(inputValue)!==-1)
    				
    				//排序
    				if(orderType!==0){
    					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>
    
    <style>
    </style>
    
    
  2. 搜索功能的实现是通过computed属性计算出新的数组,该数组通过filter对persons数组进行过滤得到。

    filter()方法使用指定的函数测试所有元素,并创建一个包含所有通过测试的元素的新数组。基本语法:

    array.filter(function(currentValue,index,arr), thisValue)
    

    参数说明:

    function(currentValue,index,arr):必须。函数,数组中的每个元素都会执行这个函数;

    currentValue:必须。当前元素的值;

    index:可选。当前元素的索引值;

    arr:可选。当前元素属于的数组对象;

    thisValue:可选。对象作为该执行回调时使用,传递给函数,用作“this”的值。

    本例中该方法的使用:

    persons.filter(p=>p.name.indexOf(inputValue)!==-1)
    

    注:=>相当于function(){return}

    即:

    persons.filter(function(p){
        return p.name.indexOf(inputValue)!==-1
    })
    

    筛选出name包含inputValue的persons数组中的数据。

  3. 排序是通过点击不同的按钮传递不同值的orderType进行判断。排序时使用sort方法。

    if(orderType!==0){
    	fPersons.sort(function(p1,p2){  //如果返回负数p1在前,返回正数p2在前
    	//1代表升序,2代表降序
    		if(orderType==2){
    			return p2.age-p1.age
    		}
    		else{
    			return p1.age-p2.age
    		}
    	})
    }
    
  4. 结果展示
    vue.js学习笔记5--列表的搜索和排序