vue 模糊查詢+排序

一、Vue 模糊查詢功能

原理:原生js的search() 方法,用於檢索字符串中指定的子字符串,或檢索與正則表達式相匹配的子字符串。若是沒有找到任何匹配的子串,則返回 -1。

input輸入框,模糊查詢

<template>
  <div id="example">
    <input type="text" v-model="searchData" placeholder="請輸入id或姓名">
    <ul>
      <li v-for="(item,index) in Newitems" :key="index">
        <span>{{item.id}}</span>
        <span>{{item.name}}</span>
        <span>{{item.time}}</span>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      searchData: "",
      items: [
        { id: "1001", name: "哈哈", time: "20170207" },
        { id: "1002", name: "呵呵", time: "20170213" },
        { id: "1103", name: "曉麗", time: "20170304" },
        { id: "1104", name: "小蘭", time: "20170112" },
        { id: "1205", name: "財務", time: "20170203" },
        { id: "1206", name: "嘻嘻", time: "20170208" },
        { id: "1307", name: "測試", time: "20170201" }
      ]
    };
  },
  computed: {
    Newitems() {
      var _this = this;
      var Newitems = [];
      _this.items.map(function(item) {
        if (
          item.id.search(_this.searchData) != -1 ||
          item.name.search(_this.searchData) != -1
        ) {
          Newitems.push(item);
        }
      });
      return Newitems;
    }
  }
};
</script>
<style scoped lang="scss">
* {
  margin: 0;
  padding: 0;
}
input {
  width: 200px;
  height: 30px;
  line-height: 30px;
  text-indent: 5px;
}
ul li {
  list-style: none;
}
ul li span {
  margin: 0 30px;
  line-height: 30px;
}
</style>

效果以下:css

圖片描述
圖片描述
圖片描述

二、排序功能

sort()方法:用於對數組的元素進行排序,並返回數組。默認排序順序是根據字符串Unicode碼點。

注意:
(1)、若是調用該方法時沒有使用參數,將按字母順序對數組中的元素進行排序.正則表達式

(2)、若是按照其餘方式排序,就須要提供比較函數,它有兩個參數 a 和 b,其返回值以下:
若 a 小於 b,在排序後的數組中 a 應該出如今 b 以前,則返回一個小於 0 的值。
若 a 等於 b,則返回 0。
若 a 大於 b,則返回一個大於 0 的值。數組

(3)、arr.sort(function(a,b){.....})函數

//升序
    function(a,b){
      return a-b;
    }
    
    
   //降序
   function(a,b){
       return b-a; 
   }

實例:測試

var arr = [
    {name:'zopp',age:0},
    {name:'gpp',age:18},
    {name:'yjj',age:8}
];

function compare(property){
    return function(a,b){
        return a[property] - b[property];
    }
}
console.log(arr.sort(compare('age')))

結果:this

圖片描述

相關文章
相關標籤/搜索