当前位置:   article > 正文

微信小程序 - picker-viewer实现省市选择器

微信小程序 - picker-viewer实现省市选择器

简介

本文会基于微信小程序picker viewer组件实现省市选择器的功能。

实现效果

实现代码

布局
  1. <picker-view value="{{value}}" bindchange="bindChange"
  2. indicator-style="height: 50px;" style="width: 100%; height: 300px;"
  3. >
  4. <picker-view-column>
  5. <view wx:for="{{provinces}}" wx:key="{{provinces}}" style="line-height: 50px; text-align: center;">{{item.name}}</view>
  6. </picker-view-column>
  7. <picker-view-column>
  8. <view wx:for="{{cities}}" wx:key="{{cities}}" style="line-height: 50px; text-align: center;">{{item.name}}</view>
  9. </picker-view-column>
  10. </picker-view>
js代码
  1. Page({
  2. data: {
  3. provinces: [],
  4. cities: [],
  5. value: [0, 0, 0],
  6. provinceCode: 0
  7. },
  8. onLoad() {
  9. var provinces = getProvinces();
  10. var cities = getCities(provinces[0].code);
  11. this.setData({
  12. provinces: provinces,
  13. cities: cities
  14. });
  15. },
  16. bindChange(e) {
  17. const value = e.detail.value;
  18. const province = this.data.provinces[value[0]];
  19. if (province.code !== this.data.provinceCode) { // 省份改变
  20. this.setData( // 设置省份状态
  21. {
  22. provinceCode: province.code
  23. }
  24. )
  25. const that = this;
  26. debounce(() => {
  27. // 加载城市
  28. const cities = getCities(province.code);
  29. that.setData({
  30. provinceCode: province.code,
  31. cities
  32. });
  33. }, 3000);
  34. return;
  35. }
  36. }
  37. })
  38. function getProvinces() {
  39. const provinces = [{
  40. name: '上海市',
  41. code: '0001'
  42. },
  43. {
  44. name: '江苏省',
  45. code: '0002'
  46. }
  47. ];
  48. return provinces;
  49. }
  50. function getCities(provinceCode) {
  51. if (provinceCode === '0001') {
  52. return [{
  53. name: '上海市',
  54. code: '10001'
  55. }]
  56. } else {
  57. return [{
  58. name: '南京市',
  59. code: '10002'
  60. },
  61. {
  62. name: '连云港市',
  63. code: '10003'
  64. }
  65. ]
  66. }
  67. }
  68. let timeout = null;
  69. function debounce(func, time) {
  70. clearTimeout(timeout);
  71. timeout = setTimeout(func, time)
  72. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/306661
推荐阅读
相关标签
  

闽ICP备14008679号