项目中遇到使用el-select组件支持远程搜索功能,且需要从下拉框中选择数据才能满足列表搜索的需求,具体实现如下:
目标:
点击”获取值“按钮后得到选中城市的车站名称和对应的城市信息
html:
<el-select class="select-keyword" v-model="cityStationName" size="mini" filterable remote clearable placeholder="请输入" @change.native="citySelectChange" @blur.native="citySelectChange"
:remote-method="cityMethod" :loading="selectLoading">
<el-option v-for="item in cityArr" :key="item.stationCode" :label="item.stationName" :value="item.stationName" @click.native="citychange(item.stationName)"></el-option>
</el-select>
<el-button @click="getVal">获取值</el-button>
js
// 获取城市数据-模拟远程查询获取城市信息
cityMethod(){
this.cityArr = [
{"stationName":"杭州东","stationPinyin":"hangzhoudong","stationShortPinyin":"hzd","stationFirstLetter":"H","station3Code":"HGH","cityCode":"3301","cityName":"杭州市","label":"杭州东,hzd,hangzhoudong,HGH","value":"杭州东","amapLng":"120.212427","amapLat":"30.291538"},
{"stationName":"杭州","stationPinyin":"hangzhou","stationShortPinyin":"hzh","stationFirstLetter":"H","station3Code":"HZH","cityCode":"3301","cityName":"杭州市","label":"杭州,hzh,hangzhou,HZH","value":"杭州","amapLng":"120.181938","amapLat":"30.243817"},
{"stationName":"杭州南","stationPinyin":"hangzhounan","stationShortPinyin":"hzn","stationFirstLetter":"H","station3Code":"XHH","cityCode":"3301","cityName":"杭州市","label":"杭州南,hzn,hangzhounan,XHH","value":"杭州南","amapLng":"120.293188","amapLat":"30.172109"},
{"stationName":"余杭","stationPinyin":"yuhang","stationShortPinyin":"yha","stationFirstLetter":"Y","station3Code":"EVH","cityCode":"3301","cityName":"杭州市","label":"余杭,yha,yuhang,EVH","value":"余杭","amapLng":"120.296839","amapLat":"30.381413"},
{"stationName":"桐庐","stationPinyin":"tonglu","stationShortPinyin":"tl","stationFirstLetter":"T","station3Code":"TLU","cityCode":"330122","cityName":"中国浙江省杭州市桐庐县","label":"桐庐,tl,tonglu,TLU","value":"桐庐","amapLng":"119.734427","amapLat":"29.787993"}
]
},
// 城市选择-输入值改变
citySelectChange(e){
console.log(e.target.value)
this.cityname = '';
},
// 出发城市选择
citychange(val) {
let selectDay = this.cityArr.find(item => item.stationName === val);
if(selectDay!==undefined){
this.cityname = selectDay.cityName;
}
},
getVal(){
console.log(`城市:${this.cityname}, 车站名称:${this.cityStationName}`)
},
注:如果不添加select的 @change.native 事件,让对应的城市名置空的话,可能会出现以下错误:
第一次选中城市后,修改输入值且没有到下拉框去选择城市数据,直接点击按钮后得到的城市信息是第一次选中的城市,和输入框输入的数据信息不匹配。