美文网首页
小程序省市区联动三种方法

小程序省市区联动三种方法

作者: zsyyyyy | 来源:发表于2021-03-11 21:16 被阅读0次

第一种,微信自带的省市区数据

<view>
  <picker mode="region" bindchange="bindRegionChange" value="{{region}}">
      <text wx:if="{{region==''}}">请选择省市区</text>
      <text wx:if="{{region!=''}}">{{region[0]}}、{{region[1]}}、{{region[2]}}</text>
  </picker>
</view>
Page({
  data: {
    region: [],// 选中的数据
  },
  //点击确定按钮
  bindRegionChange: function (e) {
    console.log(e.detail.value)
    console.log(e.detail.code)
    this.setData({
      region: e.detail.value
    })
  }
})

第二种,根据省id,ciiyid联动

        <view class="weui-cell__bd" style='text-align:right;'>
          <picker mode="multiSelector" bindchange="bindMultiPickerChange" bindcolumnchange="bindMultiPickerColumnChange"
            value="{{multiIndex}}" range="{{multiArray}}">
            <view class="picker" wx:if="{{provinceId && cityId && areaId}}">
              {{multiArray[0][multiIndex[0]]}},{{multiArray[1][multiIndex[1]]}},{{multiArray[2][multiIndex[2]]}}
            </view>
            <view wx:else>请选择省市区</view>
          </picker>
        </view>

js

import {
  queryProvince,
  queryCity,
  queryCountry,
} from "../../api/adressApi";
// pages/user/address.js
const app = getApp();
import util from '../../utils/util.js';
Page({
  data: {
    multiArray: [],
    objectMultiArray: [],
    multiIndex: [0, 0, 0],
  },
  queryCountry(cityId, areaId) {
    let that = this;
    queryCountry({
      cityId: cityId
    }).then(res => {
      let index = 2;
      let list = res.data;
      let queryCountryList = [];
      list.forEach((item, i) => {
        queryCountryList.push(item.name);
        if (item.id == areaId) {
          that.setData({
            ["multiIndex[" + index + "]"]: i,
          })
        }
      })
      that.setData({
        ["objectMultiArray[" + index + "]"]: res.data,
        ["multiArray[" + index + "]"]: queryCountryList,
      })
    })
  },
  // 请求市
  queryCity(provinceId, cityId, areaId) {
    let that = this;
    queryCity({
      provinceId: provinceId
    }).then(res => {
      let index = 1;
      let list = res.data;
      let queryCityList = [];
      list.forEach(item => {
        queryCityList.push(item.name)
      })
      that.setData({
        ["objectMultiArray[" + index + "]"]: res.data,
        ["multiArray[" + index + "]"]: queryCityList,
      })
      if (provinceId && cityId && areaId) {
        list.forEach((item, i) => {
          if (item.id == cityId) {
            that.setData({
              ["multiIndex[" + index + "]"]: i,
            })
          }
        })
        that.queryCountry(cityId, areaId);
      } else {
        let multiIndex = that.data.multiIndex;
        multiIndex[2] = 0;
        that.setData({
          multiIndex: multiIndex
        })
        that.queryCountry(res.data[0].id);
      }
    })
  },
  //请求省
  queryProvince(provinceId, cityId, areaId) {
    let that = this;
    queryProvince().then(res => {
      let list = res.data;
      let queryProvinceList = [];
      list.forEach(item => {
        queryProvinceList.push(item.name)
      })
      let index = 0;
      that.setData({
        ["objectMultiArray[" + index + "]"]: res.data,
        ["multiArray[" + index + "]"]: queryProvinceList,
      })
      if (provinceId && cityId && areaId) {
        list.forEach((item, i) => {
          if (item.id == provinceId) {
            that.setData({
              ["multiIndex[" + index + "]"]: i,
            })
          }
        })
        that.queryCity(provinceId, cityId, areaId);
      } else {
        let multiIndex = that.data.multiIndex;
        multiIndex[1] = 0;
        multiIndex[2] = 0;
        that.setData({
          multiIndex: multiIndex
        })
        that.queryCity(res.data[0].id);
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    if (options.pagetype == "add") {
      this.setData({
        pagetype: options.pagetype
      })
      this.queryProvince()
    } else {
      this.setData({
        pagetype: options.pagetype, //页面类型  edit  add
        address: options.address,
        contactName: options.contactName,
        contactPhone: options.contactPhone,
        provinceId: options.provinceId,
        cityId: options.cityId,
        areaId: options.areaId,
      })
      this.queryProvince(options.provinceId, options.cityId, options.areaId);
    }
  },

  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变,携带值为1111', e.detail.value)
    console.log(this.data.objectMultiArray[0][e.detail.value[0]])
    console.log(this.data.objectMultiArray[1][e.detail.value[1]])
    console.log(this.data.objectMultiArray[2][e.detail.value[2]])
  },
  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e.detail.column, ',值为', e.detail.value);
    var data = {
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    this.setData({
      multiIndex: data.multiIndex
    })
    switch (e.detail.column) {
      case 0:
        let provinceId = this.data.objectMultiArray[e.detail.column][e.detail.value].id;
        this.queryCity(provinceId);
        data.multiIndex[1] = 0;
        data.multiIndex[2] = 0;
        this.setData({
          multiIndex: data.multiIndex
        })
        break;
      case 1:
        let cityId = this.data.objectMultiArray[e.detail.column][e.detail.value].id;
        this.queryCountry(cityId);
        data.multiIndex[2] = 0;
        this.setData({
          multiIndex: data.multiIndex
        })
        break;
    }
    console.log([], this.data.multiIndex)
    this.setData(data);
  },
})

第三种,数据一次性返回,如下

<picker mode="multiSelector" bindchange="bindMultiPickerChange" bindcolumnchange="bindMultiPickerColumnChange"
  value="{{multiIndex}}" range="{{multiArray}}" range-key="name" catchtap="save">
  {{multiArray[0][multiIndex[0]].name}}({{multiArray[0][multiIndex[0]].id}}){{multiArray[1].length > 0 ?("," + multiArray[1][multiIndex[1]].name + "(" + multiArray[1][multiIndex[1]].id + ")"):""}}{{multiArray[2].length > 0 ?("," + multiArray[2][multiIndex[2]].name + "(" + multiArray[2][multiIndex[2]].id + ")"):""}}
</picker>
Page({
  data: {
    multiArray: [
      [{
        id: -1,
        name: "请选择省"
      }],
      [{
        id: -1,
        name: "市"
      }],
      [{
        id: -1,
        name: "区"
      }]
    ],
    multiIndex: [0, 0, 0],
    provinces: ""
  },
  getData() {
    var temp = [{
        id: 11111,
        name: "北京",
        cityList: [{
          id: 22221,
          name: "北京市",
          areaList: [{
              id: 22222,
              name: "东城区",
            },
            {
              id: 22223,
              name: "朝阳区",
            }
          ]
        }]
      },
      {
        id: 333,
        name: "上海",
        cityList: [{
          id: 22225,
          name: "上海市",
          areaList: [{
              id: 222226,
              name: "浦东",
            },
            {
              id: 22227,
              name: "浦西",
            }
          ]
        }]
      },
      {
        id: 333,
        name: "广东省",
        cityList: [{
            id: 22225,
            name: "茂名市",
            areaList: [{
                id: 222226,
                name: "电白区",
              },
              {
                id: 22227,
                name: "茂南区",
              }
            ]
          },
          {
            id: 22225,
            name: "广州市",
            areaList: [{
                id: 222226,
                name: "天河区",
              },
              {
                id: 22227,
                name: "增城区",
              }
            ]
          },
        ]
      }
    ]
    this.setData({
      provinces: temp,
      multiArray: [temp, temp[0].cityList, temp[0].cityList[0].areaList],
      multiIndex: [0, 0, 0]
    })
    console.log(this.data.multiArray)
  },

  save() {
    this.getData();
  },
  //点击确定
  bindMultiPickerChange: function (e) {
    this.setData({
      multiIndex: e.detail.value
    })
    console.log(e)
  },
  //滑动
  bindMultiPickerColumnChange: function (e) {
    console.log(e)
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    //更新滑动的第几列e.detail.column的数组下标值e.detail.value
    data.multiIndex[e.detail.column] = e.detail.value;
    //如果更新的是第一列“省”,第二列“市”和第三列“区”的数组下标置为0
    if (e.detail.column == 0) {
      data.multiIndex = [e.detail.value, 0, 0];
    } else if (e.detail.column == 1) {
      //如果更新的是第二列“市”,第一列“省”的下标不变,第三列“区”的数组下标置为0
      data.multiIndex = [data.multiIndex[0], e.detail.value, 0];
    } else if (e.detail.column == 2) {
      //如果更新的是第三列“区”,第一列“省”和第二列“市”的值均不变。
      data.multiIndex = [data.multiIndex[0], data.multiIndex[1], e.detail.value];
    }
    var temp = this.data.provinces;
    data.multiArray[0] = temp;
    if ((temp[data.multiIndex[0]].cityList).length > 0) {
      //如果第二列“市”的个数大于0,通过multiIndex变更multiArray[1]的值
      data.multiArray[1] = temp[data.multiIndex[0]].cityList;
      var areaArr = (temp[data.multiIndex[0]].cityList[data.multiIndex[1]]).areaList;
      //如果第三列“区”的个数大于0,通过multiIndex变更multiArray[2]的值;否则赋值为空数组
      data.multiArray[2] = areaArr.length > 0 ? areaArr : [];
    } else {
      //如果第二列“市”的个数不大于0,那么第二列“市”和第三列“区”都赋值为空数组
      data.multiArray[1] = [];
      data.multiArray[2] = [];
    }
    //setData更新数据
    this.setData(data);
  }
})

直接复制可用

利用vant(后台返回的所有数据)

  <van-picker columns="{{ columns }}" bind:change="onChange" />

const citys = [{
    id: 0,
    text: "硬件",
    children: [{
      id: '01',
      text: "死机",
      children: [{
        id: '001',
        text: "黑屏",
      }, {
        id: '002',
        text: "蓝屏",
      }]
    }, {
      id: '02',
      text: "卡机",
      children: [{
        id: '02',
        text: "搜索",
      }, {
        id: '002',
        text: "方法",
      }]
    }]
  },
  {
    id: '0',
    text: "硬件2",
    children: [{
      id: '01',
      text: "死机2",
      children: [{
        id: '001',
        text: "订单",
      }, {
        id: '002',
        text: "等等",
      }]
    }, {
      id: '02',
      text: "卡机2",
      children: [{
        id: '02',
        text: "镦锻",
      }, {
        id: '002',
        text: "规格",
      }]
    }]
  }
]
Page({
  /**
   * 页面的初始数据
   */
  data: {
    columns: [{
        values: citys,
        className: 'column1',
      },
      {
        values: citys[0].children,
        className: 'column2',
      },
      {
        values: citys[0].children[0].children,
        className: 'column2',
      },
    ],
  },
  onChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    var idx1 = 0, idx2 = 0, idx3 = 0;
    console.log(index, value)
    //修改第一列
    if (index == 0) {
      idx1 = picker.getColumnIndex(index);//获取第一列选中的第几个的下标
      console.log(idx1)
      picker.setColumnValues(1, citys[idx1].children);//设置对应列中所有选项
      idx2 = 0;
      idx3 = 0;
      picker.setColumnValues(2, citys[idx1].children[idx2].children);
    } else if (index == 1) {
      idx2 = picker.getColumnIndex(index);
      idx3 = 0;
      console.log( citys[idx1])
      picker.setColumnValues(2, citys[idx1].children[idx2].children);
    }
  },
})

如果w-vant需要做成联动的话;一级一级的请求回来再处理数据就可以了

相关文章

网友评论

      本文标题:小程序省市区联动三种方法

      本文链接:https://www.haomeiwen.com/subject/egioqltx.html