微信小程序实现搜索城市的功能实现附效果图和完整代码

版权声明:本文为博主原创文章,未经博主允许不得转载。如需开发微信小程序可加微信: 13977284413 https://blog.csdn.net/qq_35713752/article/details/85335964

示例图: 展示所有城市的数据,可实现模糊搜索。

先上代码

<view class="page">
  <view class="closeLocation" bindtap="goBack">
    <image src="/img/icon/closeIcon.png"></image>
  </view>
  <view class="weui-search-bar">
    <view class="weui-search-bar__form">
      <view class="weui-search-bar__box">
        <icon class="weui-icon-search_in-box" type="search" size="16"></icon>
        <input type="text" class="weui-search-bar__input" placeholder="搜索" value="{{inputVal}}" focus="{{inputShowed}}" bindconfirm='searchHandle' confirm-type="search" bindinput="searchInputCon" />
        <view class="weui-icon-clear" wx:if="{{inputVal.length > 0}}" bindtap="clearInput">
          <icon type="clear" size="16"></icon>
        </view>
      </view>
      <label class="weui-search-bar__label" hidden="{{inputShowed}}" bindtap="showInput">
        <icon class="weui-icon-search" style='margin-top:6rpx' type="search" size="16"></icon>
        <view class="weui-search-bar__text">搜索</view>
      </label>
    </view>
    <view class="weui-search-bar__cancel-btn" hidden="{{!inputShowed}}" bindtap="hideInput">取消</view>
  </view>


  <view class="currentArea" bindtap="myCity" wx:if="{{currentCity}}">
    当前定位城市:
    <text>{{currentCity}}</text>
  </view>

  <view wx:elif="{{locationLodding && !currentCity}}" class="currentArea reload loadding">
    <button>
      <view>当前定位城市:定位中</view>
      <image src="/img/icon/loading_unicom.gif"></image>
    </button>
  </view>
  <view class="currentArea reload" wx:elif="{{ldata ==false && !currentCity && !locationLodding}}">
    <view>当前定位城市:</view>
    <button open-type="openSetting" catchopensetting="locationhandler">
      <view>获取当前地理位置</view>
      <image src="/img/icon/reload.png"></image>
    </button>
  </view>
  <view class="currentArea" wx:else="{{!currentCity && locationLodding== false && ldata == false}}">
    当前定位城市:
    <text></text>
  </view>

  <view class="allCity" wx:if="{{!searchResult}}">
    <view class="provice" wx:if="{{BrowsingHistory}}">
      <view class="recently">最近访问</view>
      <view class="cityList">
        <view wx:for="{{BrowsingHistory}}" data-city="{{item.CityName}}" data-id="{{item.CityId}}" wx:key="item.CityId" bindtap="getCity">{{item.CityName}}</view>
      </view>
    </view>
    <view class="provice" wx:for="{{cityList}}" wx:key="{{item.initial}}">
      <view class="recently">{{item.initial}}</view>
      <view class="cityList">
        <view wx:for="{{item.cityInfo}}" wx:for-item="ct" wx:key="{{ct.id}}" data-city="{{ct.city}}" data-id="{{ct.id}}" bindtap="getCity">{{ct.city}}</view>
      </view>
    </view>
  </view>

  <view class="allCity" wx:if="{{searchResult}}">
    <view class="provice">
      <view class="recently">搜索结果</view>
      <view class="cityList">
        <view wx:for="{{searchResult}}" wx:for-item="ct" wx:key="{{ct.id}}" data-city="{{ct.city}}" data-id="{{ct.id}}" bindtap="getCity">{{ct.city}}</view>
      </view>
    </view>
  </view>
</view>

js

const app = getApp();
var city = require('../../utils/city.js');
var common = require('../templates/common.js');

Page({
    data: {
        searchshow : true,
        inputShowed: false,
        inputVal: "",
        locationLodding : false
    },
    onLoad:function(options){
        common.init.apply(this, []); //公共组件

        // 从修改地区过来
        if(options.editAccount){
            this.setData({
                editAccount: options.editAccount
            })
        }   
        if (!wx.getStorageSync('cityPosition')) {
          this.getLocation();
        } else {
          this.setData(wx.getStorageSync('cityPosition'))
        }
        //this.getLocation();  //获取当前位置信息
        var cityList = city.cityList(); //城市列表
        this.setData({
            cityList : cityList
        })
    },
    // 选择城市
    getCity:function(e){
        var getCityName = e.currentTarget.dataset.city;
        var getCityId = e.currentTarget.dataset.id;
        var currentCity = {
            CityName :getCityName,
            CityId : getCityId
        }
        var BrowsingHistory = wx.getStorageSync('BrowsingHistory'); 
        // 当没有浏览历史记录
        if(!BrowsingHistory){
            BrowsingHistory = [];
            BrowsingHistory.push(currentCity);
        }else{
            var checkRepeat = BrowsingHistory.find(item => {
                return item.CityId ==  getCityId;
            })
             // 当不重复时插入地区
            if(!checkRepeat){
              BrowsingHistory.unshift(currentCity);
            }
            // 当重复时,先删除再插入
            if (checkRepeat){
              BrowsingHistory = BrowsingHistory.filter((item) => {
                return item.CityId != getCityId
              })
              // console.log('BrowsingHistory',BrowsingHistory)
              BrowsingHistory.unshift(currentCity);
            }
        }

        // 当长度等于9 删除最后一个
        if (BrowsingHistory && BrowsingHistory.length == 9) {
          BrowsingHistory.pop(1);
        }

        wx.setStorageSync('currentCity',currentCity);
        // 设置一天过期时间
        var timestamp = Date.parse(new Date());
        var currentCity_expiration = timestamp + 60 * 60 * 24 * 1000;
        // var session_expiration = timestamp + 3 * 1000; //测试 10s 过期
        wx.setStorageSync("currentCity_expiration", currentCity_expiration);
        wx.setStorageSync('BrowsingHistory',BrowsingHistory);
        if(this.data.editAccount){
            let pages = getCurrentPages(); //当前页面
            let prevPage = pages[pages.length - 2]; //上一页面
            prevPage.setData({ //直接给上移页面赋值
                editAccount: this.data.editAccount
            });
            this.goBack();
        }else{
            this.goBack();
        }
        
        
    },
    // 当前定位城市
    myCity:function(){
        currentCity = this.data.currentCity;
        var currentCity = {
            CityName :currentCity,
            CityId: this.data.CityId
        }
        wx.setStorageSync('currentCity',currentCity);
        // 设置一天过期时间
        var timestamp = Date.parse(new Date());
        var currentCity_expiration = timestamp + 60 * 60 * 24 * 1000;
        wx.setStorageSync("currentCity_expiration", currentCity_expiration);
        this.goBack();
    },
    searchInputShow:function(){
        this.setData({
            searchshow : false,
            searchContext : ''
        })  
    },
    searchInputHidden:function(){
        this.setData({
            searchshow : true,
            searchContext : ''
        })  
    },
    goBack:function(){
        wx.navigateBack({
            delta: 1
        })
    },
    onShow:function(){
        var BrowsingHistory = wx.getStorageSync('BrowsingHistory');
        this.setData({
            BrowsingHistory : BrowsingHistory
        })
    },
    // 搜索 及搜索结果
    searchHandle:function(e){
        var searchContext = this.data.searchContext;
        var cityList = this.data.cityList;
        var searchArr = [];
        cityList.forEach(item =>{
            var citylist = item.cityInfo;
            citylist.forEach(value => {
                if(value.city.indexOf(searchContext) >= 0){
                    searchArr.push(value);
                }
            })
        })
        if(searchArr){
            this.setData({
                searchResult : searchArr
            })
        }
    },
    // 文本输入 事件
    searchInputCon:function(e){
        let keywords = e.detail.value;
        this.setData({
            searchContext : keywords
        })
    },
    showInput: function () {
      this.setData({
        inputShowed: true
      });
    },
    hideInput: function () {
      this.setData({
        inputVal: "",
        inputShowed: false
      });
    },
    clearInput: function () {
      this.setData({
        inputVal: ""
      });
    }
   
});

css


.closeLocation{
    height: 85rpx;
    position: relative;
}

.closeLocation image{
    width: 22rpx;
    height: 22rpx;
    position: absolute;
    right: 30rpx;
    top: 30rpx;
}
.search{
    height: 90rpx;
    background: #fff;
    width: 100%;
    position: relative;
}

.search .searchLeftText{
    width: 85rpx;
    height: 90rpx;
    position: relative;
    left: 0;top: 0;
    position: absolute;
    display: flex;
    
}
.search .searchLeftText image{
    width: 35rpx;
    height: 34rpx;
    margin-left: 35rpx;
    margin-top: 30rpx;
}
.search .undo{
    width: 100rpx;
    line-height: 90rpx;
    position: absolute;
    right: 0;
    top: 0;
    color: #55b837;
    font-size: 32rpx;
}

.search .search_input{
    height: 90rpx;
    line-height: 90rpx;
    width: 80%;
    box-sizing: border-box;
    padding-left: 85rpx;
    padding-right: 110rpx;
    background: none
}
.searchTextP{
    width: 100%;
    height: 90rpx;
}
.search .searchText{
    position: absolute;
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size:32rpx;
    color: #999;
    flex-direction: row;
    top: 0;
    left: 0;
    pointer-events:none;
}

.search .searchText image{
    width: 35rpx;
    height: 34rpx;
    margin-right: 15rpx;
}


.currentArea{
    font-size: 32rpx;
    color: #999;
    height: 90rpx;
    line-height: 90rpx;
    background: #fff;
    box-sizing: border-box;
    padding: 0 30rpx;
    margin-top: 40rpx;
}
.currentArea text{
    color: #55b837;
}

.allCity{
    height: auto;
    font-size: 28rpx;
    color: #000;
}

.allCity .provice{
    height: auto;
}

.allCity .provice .recently{
    height: 90rpx;
    line-height: 90rpx;
    color: #999999;
    padding-left: 30rpx;
}
.allCity .provice  .cityList{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}
.allCity .provice  .cityList view{
    background: #fff;
    height: 88rpx;
    border-right: 1px solid #f4f4f4;
    border-bottom: 1px solid #f4f4f4;
    width: 25%;
    overflow: hidden;
    box-sizing: border-box;
    text-align: center;
    line-height: 88rpx;
}


  .reload{
      display: flex;

  }
  
  .reload button{
    display: flex;
    padding: 0;
    margin: 0;
    background: none;
    justify-content: center;
    align-items: center;
    height: 90rpx;
    color: #999
  }
  
  .reload button image{
    width: 30rpx;
    height: 30rpx;
    margin-left: 15rpx;
  }


    .loadding button image{
    width: 25rpx;
    height: 25rpx;
  }
  /* 搜索样式 */
  .weui-search-bar{
    background: #fff
  }
  .weui-search-bar__form{
    border:none
  }
  .weui-search-bar{
    border:none
  }
  .weui-search-bar__input {
    font-size: 30rpx;
  }
  .weui-search-bar__text{
    font-size: 30rpx
  }

引用的   ../../utils/city.js

文件下载: 点击下载

猜你喜欢

转载自blog.csdn.net/qq_35713752/article/details/85335964