原理:原生js的search() 方法,用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。若是没有找到任何匹配的子串,则返回 -1。
<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