由于我的需求,对地区的选择不带区、县,官方的地区选择器无法实现,所以自己就做了一个,直接上代码
<template>
<div class="uni-city-picker">
<picker
@change="cityChange"
@columnchange="columnChange"
mode="multiSelector"
:value="cityIndex"
:range="citys"
>
<!-- 预留的插槽 -->
<slot></slot>
</picker>
</div>
</template>
<script>
import cityJson from '../js/city.json'
export default {
props: {
selectShow: {
type: Array,
default: []
}
},
data() {
return {
citys: [[], []],
cityIndex: [], // 默认
cityJson: []
}
},
mounted() {
// 省份
this.citys[0] = cityJson.map(item => {
return item.text
})
// 首先判断需不需要回显
if (this.selectShow.length > 0) {
this.cityIndex[0] = (this.citys[0] || []).findIndex(pr => pr == this.selectShow[0]) || 0
this.cityIndex[1] = (this.citys[1] || []).findIndex(ci => ci == this.selectShow[1]) || 0
} else {
this.cityIndex = [0, 0]
}
// 省份对应的城市
this.citys[1] = cityJson
.filter(item => {
return item.text == this.selectShow[0] ? this.selectShow[0] : '北京市'
})
[this.cityIndex[0]].City.map(child => {
return child.text
})
},
methods: {
cityChange(e) {
// 值改变了
const index1 = e.detail.value[0] ? e.detail.value[0] : 0
const index2 = e.detail.value[1] ? e.detail.value[1] : 0
console.log(e.detail)
const city = [cityJson[index1].text, cityJson[index1].City[index2].text]
this.$emit('cityChange', city)
},
columnChange(e) {
console.log('触发列值改变', e)
//列值改变
const index = e.detail.value
if (e.detail.column === 0) {
var citys = [...this.citys]
citys[1] = []
cityJson[index].City.forEach(child => {
citys[1].push(child.text)
})
this.citys = citys
}
}
}
}
</script>
<style lang="scss" scoped></style>
json数据,这块就粘个字段,自己上网找,很多的,找到之后将字段对应起来就好了
[
{
"City": [
{
"text": "北京市"
}
],
"text": "北京市"
},
{
"City": [
{
"text": "石家庄市"
},
{
"text": "唐山市"
},
{
"text": "秦皇岛市"
},
{
"text": "邯郸市"
},
{
"text": "邢台市"
},
{
"text": "保定市"
},
{
"text": "张家口市"
},
{
"text": "承德市"
},
{
"text": "沧州市"
},
{
"text": "廊坊市"
},
{
"text": "衡水市"
},
{
"text": "辛集市"
},
{
"text": "晋州市"
},
{
"text": "新乐市"
},
{
"text": "遵化市"
},
{
"text": "迁安市"
},
{
"text": "武安市"
},
{
"text": "南宫市"
},
{
"text": "沙河市"
},
{
"text": "涿州市"
},
{
"text": "定州市"
},
{
"text": "安国市"
},
{
"text": "高碑店市"
},
{
"text": "平泉市"
},
{
"text": "泊头市"
},
{
"text": "任丘市"
},
{
"text": "黄骅市"
},
{
"text": "河间市"
},
{
"text": "霸州市"
},
{
"text": "三河市"
},
{
"text": "深州市"
}
],
"text": "河北省"
}
]
使用
// data
data() {
return {
formAbout: {
area: ''
},
// 回显时格式 ['省','市'],例如 ['浙江省','杭州市']
selectShow: []
}
},
// 引入
import selectArea from './components/select-area/select-area.vue'
// 注册
components: {
selectArea
},
// 使用
<div class="info_item">
<span class="l_text">地区</span>
<selectArea ref="selectAreaRef" @cityChange="cityChange" :selectShow="selectShow">
<template>
<div class="r_info">
<span class="r_i_text">{{ formAbout.area || '未知' }}</span>
<image class="icon" :src="require('@/static/images/grey_arrow.png')"></image>
</div>
</template>
</selectArea>
</div>
// 成功方法
methods: {
// 选择城市
cityChange(val) {
console.log('选择城市val', val)
this.formAbout.area = val.join(' ')
}
}