浅浅的记录一下模糊查询的实现方式之一。
先看下效果图吧:
完整示例代码如下,我这里以vantUI为例子
(PS:includes方法的时候我设置了两个条件" id "和" name "因此输入id也是会匹配的哦)
<template>
<div class="generate">
<van-form ref="generateForm">
<div class="marginTop posDiv">
<van-field
name="name"
:value="name"
label="名称"
placeholder="请输入名称"
input-align="right"
autocomplete="off"
@input="onInputChange"
@click-input="isShowPicker"
/>
<div class="agentSeach" v-if="searchPicker">
<div class="closeIcon">选择名称<van-icon @click="closeSearch" name="cross" color="#b0a3a5" size="20px"/></div>
<div class="generate-formWork"
:class="{ 'generate-selected' : index == selIndex }"
v-for="(item,index) in searchList"
:key="item.id"
@click="selectName(item.id,item.name)">
<span>{{item.name}}</span>
</div>
<div v-if="searchList.length == 0 && name !== ''" class="noOptions">
<van-icon name="warning-o" size="20px"/>
暂无匹配选项
</div>
</div>
</div>
</van-form>
</div>
</template>
<script>
export default {
data() {
return {
name:'',
peopleList:[
{id:'1',name:'你好'},
{id:'2',name:'我是张张'},
{id:'3',name:'hi你好'},
{id:'4',name:'我是李李'},
{id:'5',name:'我是桃桃'}
],
searchList:[ ],
searchPicker:false,
selIndex:null
}
},
created() {
this.searchList = this.peopleList
},
methods: {
isShowPicker() {
this.searchPicker = true
},
onInputChange(val) { // 监听输入框的变化实现模糊查询
this.name = val
if (this.name === '' || this.name === null || this.name === undefined || this.selIndex!== null) { // 去除勾选状态
this.selIndex =null
}
this.searchList = this.peopleList.filter(i => {
return i.id.includes(val) || i.name.includes(val)
})
},
closeSearch() { // 关闭模糊查询
this.searchPicker= false
},
selectName(id,name) { // 赋值选中状态
this.searchList.forEach( (item,index) => {
if (item.id === id && item.name === name) {
this.selIndex = index
this.name = name
this.searchPicker = false
}
})
}
}
}
</script>
<style lang="less" scoped>
.marginTop{
margin-top: 100px;
}
.posDiv{
position: relative;
z-index: 999;
.closeIcon{
display: flex;
justify-content: center;
line-height: 40px;
/deep/.van-icon{
position: absolute;
top: 11px;
right: 10px;
}
}
.agentSeach{
width: 80%;
position: absolute;
right: 1%;
background: #fff;
box-shadow: 0 0px 5px #e3dddd;
.noOptions{
text-align: center;
color: red;
line-height: 48px;
}
/deep/.van-icon{
vertical-align: middle;
margin-right: 5px;
margin-top: -2px;
}
}
.generate-formWork{
color: #666;
display: flex;
align-items: center;
font-size: 14px;
margin: 0 24px;
height: 48px;
line-height: 20px;
padding: 5px 56px 5px 0;
word-break: break-all;
}
.generate-selected{
color: #494DF4;
background-image: url("../static/img/checked.png");
background-repeat: no-repeat;
background-size: 18px;
background-position: right;
}
}
</style>