微信小程序——城市/区县定位选择组件

前两天在实现一个城市选择器的需求的时候,在github上看到了BeijiYang同学的开源项目,觉得做的非常不错,不过是基于原生小程序写的,所以就花了点时间把他的项目基于mpvue框架改写了。方便让使用mpvue框架的同学使用。

贴一下原项目的地址,还在使用小程序自带框架的同学可以使用这个库哦 项目地址

先一起看一下实现的效果图:

城市选择器示例.gif

在改写完代码以后,我也来谈谈这个小组件里的实现逻辑。首先从布局开始,这个页面的布局结构由三个主要部分构成,页面顶部的搜索框,页面最右侧的字母列表栏,以及左边的最主要的城市列表部分。具体的页面代码我就不贴了,github链接我会放在文章尾部。

我们将地级市的数据存放到本地的city.js文件中,在这个city.js的文件中,还同时包括城市检索的首字母的数组数据,页面的城市列表以及首字母检索的数据就会从city.js中读取。在页面生命周期开始时,我们得获取当前设备的屏幕高度,用以计算右侧首字母列表的单个item高度,并且要将首字母检索的数组重组结构,最后绑定到当前页面的data下,如下的逻辑

const searchLetter = city.searchLetter;
const cityList = city.cityList();
const sysInfo = wx.getSystemInfoSync();
console.log(sysInfo);
const winHeight = sysInfo.windowHeight;
console.log(winHeight);
const itemH = winHeight / searchLetter.length;

searchLetter.map(
  (item, index) => {
    let temp = {};
    temp.name = item;
    temp.tHeight = index * itemH;
    temp.bHeight = (index + 1) * itemH;
    tempArr.push(temp);
  }
);

console.log(tempArr);

this.winHeight = winHeight;
this.itemH = itemH;
this.searchLetter = tempArr;
this.cityList = cityList;

this.getLocation();

在进入页面后,还需要定位当前的城市区县,所以有了上面👆源码的最后一行,getLocation()函数,这个函数的主要目的是为了获取到当前定位。

跟小程序原生项目不同的是我们的项目使用了Vuex来管理数据,所以原项目中需要全局保存的变量都被我使用了Vuex来管理,并且把通过腾讯地图API获取区县列表的逻辑也放入了Vuex内,让我们的组件内部只处理UI事件,变得更简洁干净,更易维护。

在点击了城市的Cell之后,接下来的操作就是通过腾讯地图API去请求接口,获取当前城市的附属区县数据,展示并可以再次点选。

/* component中的UI操作 */
// 选择城市
bindCity(e) {
  this.condition = true;
  this.changeCity({
    city: e.currentTarget.dataset.city,
    code: e.currentTarget.dataset.code
  });
  this.scrollTopId = 'selectcounty';
  this.completeList = [];

  this.selectCounty();
}

/* Vuex中的selectCounty()函数 */
// 根据城市代码 定位区县
[CITY_SELECT_COUNTY]({ commit, state }) {
console.log('正在定位区县');
let code = state.currentCityCode;
wx.request({
  url: `https://apis.map.qq.com/ws/district/v1/getchildren?&id=${code}&key=${config.key}`,
  success: function(res) {
    commit({
      type: CITY_SELECT_COUNTY,
      list: res.data.result[0]
    });
    console.log(res.data);
    console.log('请求区县成功' + `https://apis.map.qq.com/ws/district/v1/getchildren?&id=${code}&key=${config.key}`);
  },
  fail: function() {
    console.log('请求区县失败,请重试');
  }
});
},

这里就是主要的点选逻辑,接下来看看搜索框实现的搜索逻辑。我们的搜索框要求能够通过汉字或者拼音搜索,所以在搜索逻辑中,我们根据对象的short和shorter属性来进行匹配,具体的逻辑可以看如下代码:

/**
 * 搜索匹配逻辑
 */
auto() {
  let inputSd = this.inputName.trim();
  let sd = inputSd.toLowerCase();
  let num = sd.length;
  const cityList = city.cityObjs;
  let finalCityList = [];

  let temp = cityList.filter(
    item => {
      let text = item.short.slice(0, num).toLowerCase();
      // eslint-disable-next-line
      return (text && text == sd);
    }
  );

  // 在城市数据中,添加简拼到“shorter”属性,就可以实现简拼搜索
  let tempShorter = cityList.filter(
    itemShorter => {
      if (itemShorter.shorter) {
        let textShorter = itemShorter.shorter.slice(0, num).toLowerCase();
        // eslint-disable-next-line
        return (textShorter && textShorter == sd);
      }
    }
  );

  let tempChinese = cityList.filter(
    itemChinese => {
      let textChinese = itemChinese.city.slice(0, num);
      // eslint-disable-next-line
      return (textChinese && textChinese == sd);
    }
  );

  if (temp[0]) {
    temp.map(
      item => {
        let testObj = {};
        testObj.city = item.city;
        testObj.code = item.code;
        finalCityList.push(testObj);
      }
    );
    this.completeList = finalCityList;
  } else if (tempShorter[0]) {
    tempShorter.map(
      item => {
        let testObj = {};
        testObj.city = item.city;
        testObj.code = item.code;
        finalCityList.push(testObj);
      }
    );
    this.completeList = finalCityList;
  } else if (tempChinese[0]) {
    tempChinese.map(
      item => {
        let testObj = {};
        testObj.city = item.city;
        testObj.code = item.code;
        finalCityList.push(testObj);
      }
    );
    this.completeList = finalCityList;
  }
}

到这里,搜索功能也完成了,剩下无非就是各个界面的通信、以及组件与页面间的通信了,肯定也是各位同学必备的基本功了,也就不讲了。有其他疑问的可以直接阅读源码。

下面放上github仓库地址: 微信小程序-城市选择组件

如果对你有帮助,请给我一个star谢谢。

同时谢谢原作者的开源,是你的开源让使用mpvue的同学得到帮助。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,027评论 3 119
  • 本章涉及知识点1、前言2、mpVue框架简介3、项目配置和结构4、主程序入口配置5、首页页面6、城市选择页面7、搜...
    PrivateEye_zzy阅读 31,135评论 30 112
  • “秋老虎”肆无忌惮地狂妄着,窗外万物被烈日压得没了声响。哪怕是鸟雀掠过,除了轻跃的姿态和无痕的划迹,所剩唯有那丝丝...
    嫣然燕语阅读 548评论 0 2
  • 文Ⅰ王密亮 每个人,都爱微笑,把那最美的瞬间。记录下来,这将永远保存在历史的,记录里。即便人走了,但是,那微笑,还...
    王密亮阅读 142评论 0 1
  • 没有话题说真是很尴尬 不想见面和心里不喜欢就是不喜欢 生厌恶
    像你们一样阅读 228评论 0 0