输入框实现下拉搜索
程序员文章站
2024-01-01 12:13:52
...
HTML代码
<view class="search_box">
<view class="index-search">
<view class="iconfont iconcomiissousuo"></view>
<input type="text" placeholder="搜索" v-model="searchText" placeholder-class="search-text">
</view>
</view>
<view class="search-result-list" v-for="item in searchResultList" :key="item.id">
<view class="item" @click="onSelect(item.name)">{{item.name|| ""}}</view>
</view>
js设置监听属性,监听到输入的值再调用搜索接口,要注意的是在输入拼音时不能触发搜索,这就要用到正则过滤
export default {
components: {
ssSelectCity
},
data() {
return {
hotCitys: ['乌鲁木齐乌鲁木齐', '北京', '杭州', '阿克苏地区', '上海', '西安', '最多五个字啊', '香港', '日本'],
value: '成都',
searchText: '',
searchResultList: []
}
},
watch: {
searchText: {
handler: function(newVal, oldVal) {
let result = /[a-zA-Z]/.test(newVal);
if (!result) {
this.searchResult();
}
}
}
},
created() {
this.value = uni.getStorageSync('newCity');
},
methods: {
onSelect(selectCity) {
console.log(selectCity);
uni.setStorage({
key: 'newCity',
data: selectCity
})
uni.setStorage({
key: 'selectCity',
data: 'selected'
})
uni.switchTab({
url: '/pages/tabBar/index/index'
})
},
//
searchResult() {
let that = this;
that.utils.sendRequest(`api/publicc/search_city?keyword=${that.searchText}`, 'GET', {}).then((res) => {
console.log(res);
if (res.data.code == 1) {
if (res.data.data.length != 0) {
that.searchResultList = res.data.data;
console.log(that.searchResultList);
} else {
if (that.searchText != "") {
uni.showToast({
title: '未找到相关结果',
icon: 'none',
duration: 1000
});
that.searchResultList = [];
}else{
that.searchResultList = [];
}
}
} else if (res.data.code == 0) {
uni.showToast({
title: res.data.msg,
icon: 'none',
duration: 1500
});
}
})
}
}
}