支持远程搜索的select框是一个必备的功能,本文分享如何使用elmentui 实现从后端flask获取数据的el-autocomplete
控件。类似输入一个京字,就从数据库查询所有的城市,模糊匹配到带有京字的城市,并且可以选中。
1 前端
前端要使用到el-autocomplete控件,输入控件后的提示通过querySearch实现, 选择之后的操作通过handleSelect实现。
<el-autocompletev-model="city":fetch-suggestions="querySearch"placeholder="请输入城市名称"@select="handleSelect"style="width: 300px; margin-left: 10px;"clearable></el-autocomplete>data(){return{city: '',}},methods: {// cb 为回调函数需要把后端返回的值传给它querySearch(queryString, cb) {// 发送请求到Flask后端获取模糊搜索结果getCities(queryString).then(res=>{// 返回数据的形式是 [{value:'xxxx'}, {value:'yyyyy'} ...] 这样cb(res.data.data)})},handleSelect(item) {this.city = item.value; // 选择后将城市名存储在city变量中this.$message('加载'+this.city+'数据成功', 'success', 3000)},},
getCities
// 获取城市列表
export function getCities(queryString){return request({url: `/tour/cities`,method: 'get',params:{ keyword: queryString }});
}
2 后端
我们要读取景点列表中所有的城市数据,形成一个[{value:‘xxxx’}, {value:‘yyyyy’} …] 形式的数据返回就可以。
# 获取城市
@main.route('/tour/cities', methods=['GET'])
def search_cities():keyword = request.args.get('keyword', '')try:# 查询并去重城市名称,使用SQLAlchemy的distinctcities = Tour.query.with_entities(distinct(Tour.city)).filter(Tour.city.ilike(f'%{keyword}%')).all()# 将结果转换为字典列表result = [{'value': city[0]} for city in cities]return make_response(code=0, data=result)except Exception as e:return make_response(code=1, message=str(e))
3 实现效果
下一期就来做根据选择框的数据来加载echarts-wordcloud词云(分析景点精选评论文本主题词)