WXL
昨天 c80bc467a41daa6cbae4e5515a300a8ca98cfeaa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<template>
  <view>
    <view class="area-select-display" @click="openPicker">
      <text :class="{ placeholder: !displayText }">{{ displayText || '请选择省/市/区' }}</text>
      <text class="icon-arrow">›</text>
    </view>
 
    <u-picker
      ref="pickerRef"
      :show="pickerShow"
      :columns="columns"
      keyName="name"
      @confirm="onConfirm"
      @change="onChange"
      @cancel="pickerShow = false"
      title="选择地区"
    />
  </view>
</template>
 
<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
 
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  }
})
 
const emit = defineEmits(['update:modelValue', 'change'])
 
const pickerShow = ref(false)
const columns = ref([[], [], []])
const pickerRef = ref(null)
 
// 存储数据
const provinceList = ref([])      // [{ name, code, cities }]
const cityMap = ref(new Map())     // provinceCode -> cities
const districtMap = ref(new Map()) // cityCode -> districts
 
const displayText = computed(() => {
  const { sheng, shi, qu } = props.modelValue
  if (sheng && shi && qu) return `${sheng} ${shi} ${qu}`
  if (sheng && shi) return `${sheng} ${shi}`
  if (sheng) return sheng
  return ''
})
 
// 加载地区数据
const loadRegionData = async () => {
  try {
    const res = await uni.$uapi.get('/project/dict/treeselect')
    if (res.code === 200 && res.data) {
      buildMappings(res.data)
    } else {
      console.error('获取地区数据失败', res)
    }
  } catch (error) {
    console.error('地区数据接口异常', error)
  }
}
 
// 构建映射
const buildMappings = (treeData) => {
  provinceList.value = []
  cityMap.value.clear()
  districtMap.value.clear()
 
  treeData.forEach(province => {
    const provinceName = province.areaname
    const provinceCode = province.areacode
    const cities = []
 
    if (province.subarea && province.subarea.length) {
      province.subarea.forEach(city => {
        const cityName = city.areaname
        const cityCode = city.areacode
        const districts = []
 
        if (city.subarea && city.subarea.length) {
          city.subarea.forEach(district => {
            districts.push({
              name: district.areaname,
              code: district.areacode
            })
          })
        }
        districtMap.value.set(cityCode, districts)
        cities.push({
          name: cityName,
          code: cityCode,
          districts: districts
        })
      })
    }
 
    provinceList.value.push({
      name: provinceName,
      code: provinceCode,
      cities: cities
    })
    cityMap.value.set(provinceCode, cities)
  })
 
  // 初始化第一列
  const firstColumn = provinceList.value.map(p => p.name)
  columns.value = [firstColumn, [], []]
}
 
// 选择器变化事件(使用 setColumnValues)
const onChange = (e) => {
  const { columnIndex, value, index, picker = pickerRef.value } = e
  if (columnIndex === 0) {
    // 省变化:更新第二列(市)
    const province = provinceList.value[index]
    if (province && province.cities) {
      const cityNames = province.cities.map(c => c.name)
      picker.setColumnValues(1, cityNames)
      // 清空第三列
      picker.setColumnValues(2, [])
    } else {
      picker.setColumnValues(1, [])
      picker.setColumnValues(2, [])
    }
  } else if (columnIndex === 1) {
    // 市变化:更新第三列(区县)
    const provinceIdx = e.values[0] ? provinceList.value.findIndex(p => p.name === e.values[0]) : -1
    if (provinceIdx !== -1) {
      const province = provinceList.value[provinceIdx]
      const city = province.cities[index]
      if (city && city.districts) {
        const districtNames = city.districts.map(d => d.name)
        picker.setColumnValues(2, districtNames)
      } else {
        picker.setColumnValues(2, [])
      }
    } else {
      picker.setColumnValues(2, [])
    }
  }
}
 
// 打开选择器(支持回显)
const openPicker = async () => {
  pickerShow.value = true
  await nextTick()
  const picker = pickerRef.value
  if (!picker) return
 
  const { sheng, shi, qu } = props.modelValue
  if (sheng) {
    // 查找省索引
    const provinceIdx = provinceList.value.findIndex(p => p.name === sheng)
    if (provinceIdx !== -1) {
      const province = provinceList.value[provinceIdx]
      // 设置第一列选中
      picker.setIndexes([provinceIdx, 0, 0])
      // 更新第二列数据
      const cityNames = province.cities.map(c => c.name)
      picker.setColumnValues(1, cityNames)
      if (shi) {
        const cityIdx = province.cities.findIndex(c => c.name === shi)
        if (cityIdx !== -1) {
          // 设置第二列选中
          picker.setIndexes([provinceIdx, cityIdx, 0])
          // 更新第三列数据
          const city = province.cities[cityIdx]
          const districtNames = city.districts.map(d => d.name)
          picker.setColumnValues(2, districtNames)
          if (qu) {
            const districtIdx = city.districts.findIndex(d => d.name === qu)
            if (districtIdx !== -1) {
              picker.setIndexes([provinceIdx, cityIdx, districtIdx])
            }
          }
        }
      }
    } else {
      // 未找到,重置
      picker.setColumnValues(1, [])
      picker.setColumnValues(2, [])
      picker.setIndexes([0, 0, 0])
    }
  } else {
    // 无预选,重置列
    picker.setColumnValues(1, [])
    picker.setColumnValues(2, [])
    picker.setIndexes([0, 0, 0])
  }
}
 
// 确认选择
const onConfirm = (e) => {
  const { value: values, indexes } = e
  const provinceName = values[0]
  const cityName = values[1]
  const districtName = values[2]
  const province = provinceList.value.find(p => p.name === provinceName)
  if (province) {
    const city = province.cities.find(c => c.name === cityName)
    const district = city ? city.districts.find(d => d.name === districtName) : null
    const newValue = {
      sheng: province.name,
      shi: city ? city.name : '',
      qu: district ? district.name : '',
      provinceCode: province.code,
      cityCode: city ? city.code : '',
      districtCode: district ? district.code : ''
    }
    emit('update:modelValue', newValue)
    emit('change', newValue)
  }
  pickerShow.value = false
}
 
defineExpose({ refresh: loadRegionData })
 
onMounted(() => {
  loadRegionData()
})
</script>
 
<style lang="scss" scoped>
.area-select-display {
  background: #fafafa;
  border-radius: 12rpx;
  padding: 20rpx 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 2rpx solid #e5e5e7;
  transition: border-color 0.25s;
  &:active {
    border-color: #0f95b0;
  }
  .placeholder {
    color: #b0b0b0;
  }
  .icon-arrow {
    font-size: 34rpx;
    color: #86868b;
    transform: rotate(90deg);
  }
}
</style>