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

简介

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

实现效果

实现代码

布局
html 复制代码
<picker-view value="{{value}}" bindchange="bindChange"
indicator-style="height: 50px;" style="width: 100%; height: 300px;" 
>

  <picker-view-column>
    <view wx:for="{{provinces}}" wx:key="{{provinces}}" style="line-height: 50px; text-align: center;">{{item.name}}</view>
  </picker-view-column>
  <picker-view-column>
    <view wx:for="{{cities}}" wx:key="{{cities}}" style="line-height: 50px; text-align: center;">{{item.name}}</view>
  </picker-view-column>

</picker-view>
js代码
javascript 复制代码
Page({
  data: {
    provinces: [],
    cities: [],
    value: [0, 0, 0],
    provinceCode: 0
  },
  onLoad() {
    var provinces = getProvinces();
    var cities = getCities(provinces[0].code);
    this.setData({
      provinces: provinces,
      cities: cities
    });
  },
  bindChange(e) {
    const value = e.detail.value;
    const province = this.data.provinces[value[0]];
    if (province.code !== this.data.provinceCode) { // 省份改变
      this.setData( // 设置省份状态
        {
          provinceCode: province.code
        }
      )
      const that = this;
      debounce(() => {
        // 加载城市
        const cities = getCities(province.code);
        that.setData({
          provinceCode: province.code,
          cities
        });
      }, 3000);
      return;
    }

  }
})

function getProvinces() {
  const provinces = [{
      name: '上海市',
      code: '0001'
    },
    {
      name: '江苏省',
      code: '0002'
    }
  ];
  return provinces;
}

function getCities(provinceCode) {

  if (provinceCode === '0001') {
    return [{
      name: '上海市',
      code: '10001'
    }]
  } else {
    return [{
        name: '南京市',
        code: '10002'
      },
      {
        name: '连云港市',
        code: '10003'
      }
    ]
  }
}

let timeout = null;
function debounce(func, time) {
  clearTimeout(timeout);
  timeout = setTimeout(func, time)
}
相关推荐
小羊Yveesss12 小时前
2026年微信小程序搭建一般需要多长时间?不同方案周期和延期点
微信小程序·小程序
小羊Yveesss16 小时前
2026年微信小程序搭建算什么费用?年费、设计费、开发费和维护费
微信小程序·小程序
小羊Yveesss2 天前
2026年微信小程序后端怎么搭建?后台、数据、接口和运维怎么选
运维·微信小程序·小程序
小皮虾2 天前
小程序首页性能优化实战:从 4 秒到 1.8 秒
前端·微信小程序
衍生星球3 天前
SpringBoot3 + Vue3 + 微信小程序如何学习,以及学哪些技术,组件
sql·微信小程序·uni-app·vue·springboot
新华财经频道4 天前
2026微信小程序搭建平台实测测评,优缺点解析
微信小程序·小程序
kidding7235 天前
旋转大转盘小程序
前端·css·微信小程序·小程序·前端框架
这是个栗子6 天前
uni-app 微信小程序开发:常用事件指令(@xxx)(一)
微信小程序·小程序·uni-app
博客zhu虎康9 天前
小程序:微信小程序连接打印机蓝牙打印全攻略
微信小程序·小程序·notepad++
tcdos9 天前
不止扫码 — 微信生态深度融合(登录 + 支付 + 消息)
后端·微信小程序