效果图
![效果图](https://i-blog.csdnimg.cn/blog_migrate/d7b4e347fe057062b6fa23426d95e42f.gif)
功能简介
- 实现搜索城市的功能,点击搜索结果可提示对应的城市,方便二次开发
- 热门城市的显示(数据是写死的)
项目结构
代码
citysearch.wxml
<view class="search-box">
<icon type="search" size="18" color="#0081ff"></icon>
<input bindinput="bindKeyInput" placeholder="输入城市名"></input>
</view>
<view class="result-box">
<view class="result-item" data-city="{{item.citysName}}" bindtap="onclick" wx:for="{{result}}" wx:key="index">
{{item.txt}}
</view>
</view>
<view class="hotcity-title" wx:if="{{result.length==0}}">
<view class="title-icon"></view>
<view class="title-txt">热门城市</view>
</view>
<view class="hotcity-box" wx:if="{{result.length==0}}">
<view class="hotcity-item" data-city="{{item}}" bindtap="onclick" wx:for="{{hotcity}}" wx:key="index">
{{item}}
</view>
</view>
citysearch.wxss
.search-box{
margin: 32rpx 32rpx 18rpx 32rpx;
border-radius: 18rpx;
box-shadow: 0.1rem 0.1rem 0.5rem rgba(0, 0, 0, 0.15);
background-color: white;
display: flex;
overflow: hidden;
align-items: center;
}
.search-box input{
flex: 1;
padding:18rpx 32rpx;
}
.search-box icon{
padding: 18rpx 0 18rpx 18rpx;
}
.result-box{
border-top: gainsboro 1rpx solid;
}
.result-item{
display: flex;
padding: 32rpx;
border-radius: 8rpx;
font-size: 28rpx;
border-bottom: gainsboro 1rpx solid;
background-color: white;
justify-content: space-between;
align-items: center;
}
.hotcity-title{
display: flex;
padding: 18rpx 32rpx;
}
.title-icon {
width: 10rpx;
margin: 12rpx 16rpx 8rpx 0;
background-color: #0081ff;
border-radius: 50rpx;
}
.title-txt {
font-weight: bold;
font-size: 32rpx;
}
.hotcity-box{
margin: 32rpx;
display: grid;
grid-template-columns: repeat(3, 218rpx);
grid-row-gap: 32rpx;
grid-column-gap: 18rpx;
}
.hotcity-item{
padding: 12rpx 0;
border-radius: 8rpx;
text-align: center;
color: #333333;
background-color: #f0f0f0;
}
citysearch.js
const provinces = require('./provinces.js') //引入城市数组
Page({
data: {
hotcity: ["广州市", "北京市", "深圳市", "上海市", "南京市", "杭州市", "武汉市", ],
result: []
},
/**
* 搜索城市
*/
bindKeyInput(e) {
var city = e.detail.value
//如果输入为空,返回
if (city == '') {
this.setData({
result: []
})
return
}
var result = []
provinces.provinces.forEach(item => {
item.citys.forEach(res => {
if (res.citysName.indexOf(city) == 0) { //使用indexOf()=0 实现是否以...开头
result.push({
citysName: res.citysName,
txt: res.citysName + "," + item.provinceName,
})
}
})
})
this.setData({
result: result
})
},
/**
* 单击结果
*/
onclick(e){
var city = e.currentTarget.dataset.city
wx.showToast({
icon: 'none',
title: city,
})
}
})
citysearch.json
{
"usingComponents": {},
"navigationBarTitleText": "城市搜索"
}
provinces.js
代码太多就不复制到这里了,请前往provinces.js,全选复制粘贴到你新建的provinces.js或者Ctrl+S
下载到你的目录里。
留言
如果有什么不懂或者有BUG,请在评论区留言或者加我qq1354760865,我会在第一时间回复!!!
目前正在学习前端,微信小程序…欢迎关注,一起学习!!!
欢迎访问我的小程序