一、数组实现模糊搜索
CDN引入vue:
<link href="https://cdn.bootcss.com/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
Html里面代码:
<div class="container"> <div class="row"> <div class="col-lg-6" style="margin: 20px"> <div class="input-group"> <span class="input-group-btn"> <button class="btn btn-default" type="button">搜索</button> </span> <input type="text" v-model="text" class="form-control" placeholder="Search for..." /> </div> </div> <table class="table table-hover"> <thead> <tr> <th>序号</th> <th>姓名</th> <th>性别</th> <th>爱好</th> <th>年龄</th> </tr> </thead> <tbody> <tr v-for="(item, i) in searchResult" :key="i"> <td>{{ i + 1 }}</td> <td>{{ item.name }}</td> <td>{{ item.sex }}</td> <td>{{ item.hobby }}</td> <td>{{ item.age }}</td> </tr> </tbody> </table> </div> </div>
Js代码:
var vm = new Vue({
el: '.container',
data: {
text: '',
info: [{
name: '雷森',
sex: '男',
hobby: '打篮球',
age: '18'
},
{
name: '刘伟',
sex: '男',
hobby: '旅游',
age: '24'
},
{
name: '刘微',
sex: '女',
hobby: '旅游',
age: '24'
},
{
name: '胡汉三',
sex: '男',
hobby: '美食',
age: '30'
},
{
name: '张艺',
sex: '女',
hobby: '看韩剧',
age: '24'
},
{
name: '欧阳',
sex: '女',
hobby: '环游世界',
age: '25'
}]
},
computed: {
searchResult() {
if (this.text) {
// console.log(this.info)
return this.info.filter( item =>item.name.indexOf(this.text) != -1 || item.hobby.indexOf(this.text) != -1 || item.age.indexOf(this.text) != -1 );
} else {
return this.info;
}
}
}
}