微信小程序 - 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)
}
相关推荐
誰在花里胡哨18 小时前
微信小程序实现陀螺仪卡片景深效果
前端·微信小程序·动效
XXXFIRE19 小时前
微信小程序开发实战笔记:全流程梳理
前端·微信小程序
Thomas游戏开发20 小时前
Cocos Creator 面试技巧分享
面试·微信小程序·cocos creator
小小愿望1 天前
微信小程序开发实战:图片转 Base64 全解析
前端·微信小程序
两个月菜鸟1 天前
vue+微信小程序五角星
vue.js·微信小程序·notepad++
Hashan1 天前
微信小程序:扁平化的无限级树
前端·微信小程序·uni-app
程序员陆通2 天前
零基础AI编程开发微信小程序赚流量主广告实战
微信小程序·小程序·ai编程
编程猪猪侠2 天前
解决uni-app微信小程序编译报错:unexpected character `1`
微信小程序·小程序·uni-app
Hashan3 天前
微信小程序:实现证件OCR识别
前端·vue.js·微信小程序
一念杂记3 天前
【实战系列3】免费可商用微信商城小程序开发——商品管理和展示
后端·微信小程序·开源