先上效果图

代码
<template>
<view>
<button @click="changeArea">弹出地址选择器</button>
<u-picker :show="show" ref="uPicker" :columns="cityList" @confirm="cityConfirm" @change="changeHandler" @cancel="show = false"></u-picker>
</view>
</template>
<script setup>
import cityData from '@/city.js';
import { ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
const ann = ref(true);
const model1 = reactive({
userInfo: {
name: '',
sex: ''
}
});
//
const show = ref(false);
const cityName = ref('请选择地区'); // 城市选择器
const areaname = ref();
const cityList = ref([]);
const cityLevel1 = ref([]);
const cityLevel2 = ref([]);
const cityLevel3 = ref([]);
onLoad(() => {
// 城市选择器初始化
initCityData();
});
//控制弹出层的显示和隐藏
const changeArea = () => {
show.value = !show.value;
};
// 城市选择器
const initCityData = () => {
// 遍历城市js
cityData.forEach((item1, index1) => {
let temp2 = [];
cityLevel1.value.push(item1.provinceName);
let temp4 = [];
let temp3 = [];
// 遍历市
item1.cities.forEach((item2, index2) => {
temp2.push(item2.cityName);
// 遍历区
item2.counties.forEach((item3, index3) => {
temp3.push(item3.countyName);
});
temp4[index2] = temp3;
temp3 = [];
});
cityLevel3.value[index1] = temp4;
cityLevel2.value[index1] = temp2;
});
// 选择器默认城市
cityList.value.push(cityLevel1.value, cityLevel2.value[0], cityLevel3.value[0][0]);
};
// 选中时执行
const changeHandler = (e) => {
const {
columnIndex,
index,
indexs,
value,
values,
// 微信小程序无法将picker实例传出来,只能通过ref操作
picker = this.$refs.uPicker
} = e;
if (columnIndex === 0) {
// 选择第一列数据时
// 设置第二列关联数据
picker.setColumnValues(1, cityLevel2.value[index]);
// 设置第三列关联数据
picker.setColumnValues(2, cityLevel3.value[index][columnIndex]);
} else if (columnIndex === 1) {
// 选择第二列数据时
// 设置第三列关联数据
picker.setColumnValues(2, cityLevel3.value[indexs[0]][index]);
}
};
// 单击确认按钮时执行
const cityConfirm = (e) => {
// 输出数组 [省, 市, 区]
console.log(e.value);
areaname.value = e.value;
cityName.value = e.value.join('-');
// 隐藏城市选择器
console.log(cityName.value);
show.value = false;
};
</script>
最后是city.js文件
2439

被折叠的 条评论
为什么被折叠?



