1.代码如下
<template><view class="container"><form><picker mode="multiSelector" :range="multiArray" @change="onMultiChange" @columnchange="onMultiColumnChange"><view class="picker"><text>{{ multiArray[0][selectedIndex[0]] }}</text><text class="iconfont icon-down"></text><text>{{ multiArray[1][selectedIndex[1]] }}</text><text class="iconfont icon-down"></text></view></picker><view class="result"><text>最终选择结果:</text><text>{{ result }}</text></view></form></view>
</template><script setup>
import { ref, onMounted } from 'vue'// 数据定义
const multiArray = ref([]) // 两列联动数据
const selectedIndex = ref([0, 0]) // 当前选中的索引,市、区
const cityList = ref([{name: "广州市",districtList: ["荔湾区", "越秀区", "海珠区", "天河区", "白云区", "黄埔区", "番禺区", "花都区", "南沙区", "增城区", "从化区"]},{name: "深圳市",districtList: ["罗湖区", "福田区", "南山区", "宝安区", "龙岗区", "盐田区", "龙华区", "坪山区", "光明区", "大鹏新区"]}
])const result = ref('') // 最终结果// 初始化多列联动数据
onMounted(() => {multiArray.value = [cityList.value.map(city => city.name), // 市列表,广州市和深圳市cityList.value[0].districtList // 区列表,初始化为广州市的区]updateResult()
})// 更新最终结果
const updateResult = () => {const provinceName = '广东省' // 假设只有一个省,可以根据实际情况调整const selectedCity = cityList.value[selectedIndex.value[0]]const selectedDistrict = selectedCity.districtList[selectedIndex.value[1]]result.value = `${provinceName} - ${selectedCity.name} - ${selectedDistrict}`
}// 当用户选择市或区时,更新最终结果
const onMultiChange = (e) => {selectedIndex.value = e.detail.valueconst selectedCity = cityList.value[selectedIndex.value[0]]multiArray.value[1] = selectedCity.districtListupdateResult()
}// 当用户改变市时,更新区数据并更新最终结果
const onMultiColumnChange = (e) => {const column = e.detail.columnconst value = e.detail.valueif (column === 0) {const selectedCity = cityList.value[value]multiArray.value[1] = selectedCity.districtListselectedIndex.value[1] = 0 // 重置区索引为0}updateResult()
}
</script><style scoped>
.container {padding: 20px;
}
.picker {padding: 10px;background-color: #f0f0f0;border-radius: 5px;text-align: center;margin-bottom: 20px;
}
.iconfont {margin-left: 10px;
}
.result {margin-top: 20px;font-size: 16px;
}
</style>
2.当前默认值为 selectedIndex = ref([0, 0]) 需要为空值改为-1,-1后给uni-picker加个高度