uniapp 小程序实现模糊查询/搜索
适用场景
- 适用于选项过多需要进行大量人工选择/需要在前端进行过滤的场景
实现思路
- 通过监听搜索框输入进行实时匹配,运用数组过滤方法
示例
实现过程
- template
<template>
<view class="search-box">
<view class="input-box">
<input type="text" v-model="keyword" placeholder="请输入你想选择的颜色" @input="handleInput" />
<image src="/static/images/icons/qingchu.png" @click="onClears"></image>
</view>
<view class="search-btn" @click="searchResult">搜索</view>
</view>
<view class="list">
<multiples-others :dataList="colorType" v-model="answer"></multiples-others>
</view>
</template>
- script
<script>
// 引入颜色类型
import {
type
} from '@/global/options.js'
// 设置变量存储 type
const keeptype = type
export default {
data() {
return {
keyword: '', //关键词匹配
colorType: type
};
},
methods: {
// 搜索结果
searchResult() {
this.shandleInput()
},
// 清空答案
onClears() {
this.keyword = ''
this.handleInput()
},
// 实时匹配
handleInput(e) {
let value = ''
if (e) {
value = e.detail.value
} else if (this.keyword) {
value = this.keyword
} else {
value = ''
this.matchResult(value, 100)
return
}
this.matchResult(value, 400)
},
matchResult(value, delay) {
console.log(value);
// 清除 timer 对应的延时器
clearTimeout(this.timer)
// 重新启动一个延时器,并把 timerId 赋值给 this.timer
this.timer = setTimeout(() => {
this.colorType = keeptype.filter(item => item.includes(value))
}, delay)
},
}
}
</script>
- css
<style lang="scss">
// 搜索框
.search-box {
background-color: rgb(242, 242, 242);
padding: 15upx 2.5%;
display: flex;
justify-content: space-between;
// position: sticky;
margin-bottom: 20rpx;
// top: 0;
}
.search-box .mSearch-input-box {
width: 100%;
}
.search-box .input-box {
width: 85%;
flex-shrink: 1;
display: flex;
justify-content: center;
align-items: center;
}
.search_text {
font-size: 28rpx;
color: #B6B6C6;
}
.input-box {
position: relative;
height: 60upx;
font-size: 28rpx;
border: 0;
border-radius: 60upx;
-webkit-appearance: none;
appearance: none;
padding: 0 3%;
margin: 0;
background-color: #ffffff;
}
.search-box .search-btn {
width: 15%;
margin: 0 0 0 2%;
display: flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
font-size: 28rpx;
color: #fff;
background-color: #5f98ee;
border-radius: 60upx;
}
.search-box .input-box>input {
width: 95%;
height: 60upx;
font-size: 28rpx;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
margin: 0;
background-color: #ffffff;
border-bottom: none;
}
.input-box image {
height: 40upx;
width: 40upx;
float: right;
position: absolute;
right: 2%;
top: 50%;
transform: translateY(-50%);
z-index: 100;
}
.list {
padding: 20rpx;
}
</style>