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

简介

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

实现效果

微信小程序 - picker-viewer实现省市选择器_第1张图片

实现代码

布局


  
    {{item.name}}
  
  
    {{item.name}}
  

js代码

借助observers ,监听 provincecode的变化,实现cities的更新。

Page({
  data: {
    provinces: [],
    cities: [],
    value: [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]];
    this.setData({
        provinceCode: province.code
    });
  },
  behaviors:[Behavior(
    {
        observers:{
            'provinceCode':function(provinceCode){
                debounce(() => {
                // 加载城市
                const cities = getCities(province.code);
                this.setData({
                   provinceCode: provinceCode,
                   cities
                 });
                }, 3000);
            }
        }

    })
  ],
})

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)
}

你可能感兴趣的:(微信小程序,微信小程序)