uView2.0 u-picker三级联动省市区

时间:2025-02-23 07:32:53
import { areaList } from '@/utils/address-data' export default { data(){ return { //地址展示框 addressShow: false, getLocationState: false, //要提交的表单信息 userAddress: {}, //三级联动组件展示框 addressShow:false, //省市区数据 columns: [ [], [], [] ] } }, created() { this.columns[0] = areaList; this.columns[1] = areaList[0].cities; this.columns[2] = areaList[0].cities[0].districts; }, computed: { getAddressText() { return () => this.userAddress.province + ' ' + this.userAddress.city + ' ' + this.userAddress.area; } }, methods:{ pickerCancel() { //隐藏联动展示框 this.addressShow = false; //重置联动数据为初始状态 this.$refs.uPicker.setIndexs([0, 0, 0], true); this.$refs.uPicker.setColumnValues(0, areaList); this.$refs.uPicker.setColumnValues(1, areaList[0].cities); this.$refs.uPicker.setColumnValues(2, areaList[0].cities[0].districts); }, }, //三级联动框滑动选择后触发的事件 changeHandler(e) { const { columnIndex, value, values, // values为当前变化列的数组内容 index, indexs, // 微信小程序无法将picker实例传出来,只能通过ref操作 picker = this.$refs.uPicker } = e // 当第一列值发生变化时,变化第二列(后一列)对应的选项 if (columnIndex === 0) { // picker为选择器this实例,变化第二列对应的选项 picker.setColumnValues(1, areaList[index].cities) picker.setColumnValues(2, areaList[indexs[0]].cities[0].districts) } else if (columnIndex === 1) { // picker为选择器this实例,变化第三列对应的选项 picker.setColumnValues(2, areaList[indexs[0]].cities[indexs[1]].districts) } }, // 点击确定事件,回调参数为包含columnIndex、value、values confirm(e) { console.log('confirm', e) //省 this.userAddress.province = e.value[0].name; //市 this.userAddress.city = e.value[1].name; //区 this.userAddress.area = e.value[2].name; //区域代码 this.userAddress.regionId = e.value[2].id; this.pickerCancel(); }, poptanqi() { let that = this; if (!that.getLocationState) { uni.showLoading({ title: '加载中' }); uni.getLocation({ type: 'wgs84', isHighAccuracy: true, success: function(res) { console.log('当前位置的经度:' + res.longitude); console.log('当前位置的纬度:' + res.latitude); //自定义的接口,按照腾讯位置服务文档接入 getAdInfoByLngAndLat({ longitude: res.longitude, latitude: res.latitude }).then(res2 => { if (res2.data.head.code == '0') { let resData = res2.data.details; if (resData.status == 0) { that.$set(that.userAddress, 'province', resData.result.ad_info .province); that.$set(that.userAddress, 'city', resData.result.ad_info .city); that.$set(that.userAddress, 'area', resData.result.ad_info .district); that.$set(that.userAddress, 'regionId', resData.result.ad_info .adcode + '000'); that.getLocationState = true; } else { that.$nextTick(()=>{ that.$refs["cityPicker"].show(); }) } } else { that.$nextTick(()=>{ that.$refs["cityPicker"].show(); }) } }); }, fail(err) { that.addressShow = true; console.log('遇到错误!'); console.log(err); }, complete() { uni.hideLoading(); } }); } else { that.$nextTick(()=>{ this.$refs["cityPicker"].show(); }) } }, }