赞
踩
本文会基于微信小程序picker viewer组件实现省市选择器的功能。
- <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>
- 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)
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。