1、效果
省份没选之前,市与区禁选,同理市未选择,区也是禁用的重新选择省,市与区的也会清空,同理重新选择市,区也会重置,完整代码地址
选择的时候就是下面这样的
2、主要逻辑代码
html相关代码
<template>
<div class="area-component">
<!-- 省 -->
<el-select
placeholder="请选择省份"
v-model="state.params.province"
clearable
>
<el-option
v-for="item in state.showData.province"
:key="item.code"
:label="item.name"
:value="item.code"
/>
</el-select>
<!-- 市 -->
<el-select
placeholder="请选择城市"
style="margin: 0 10px;"
:disabled="!state.params.province"
v-model="state.params.city"
clearable
>
<el-option
v-for="item in state.showData.cities"
:key="item.code"
:label="item.name"
:value="item.code"
/>
</el-select>
<!-- 区 -->
<el-select
placeholder="请选择区"
:disabled="!state.params.province || !state.params.city"
v-model="state.params.area"
clearable
>
<el-option
v-for="item in state.showData.areas"
:key="item.code"
:label="item.name"
:value="item.code"
/>
</el-select>
</div>
</template>
逻辑处理部分
import { reactive, onBeforeMount, computed, watch } from 'vue'
import areaData from '@/components/myArea/data/pca-code.json'
// 定义数据类型
export interface areaType {
code: string
name: string
children?: areaType[]
}
// 父组件爱传过来的事件,用于接收省市区选择后的数据
const emits = defineEmits<{
(e: 'areaChange', value: any):void
}>()
const state = reactive({
// 用于展示的省市区数据
showData:{
province: [] as areaType[],
cities: [] as areaType[],
areas: [] as areaType[],
},
// 最终选择的省市区
params:{
province: undefined,
city: undefined,
area: undefined
}
})
// 准备省市区展示数据
onBeforeMount(()=>{
state.showData.province = areaData.map((item) => ({code: item.code, name:item.name}))
})
state.showData.cities = computed(()=>{
return areaData.find((item)=>item.code === state.params.province)?.children
}) as any
state.showData.areas = computed(()=>{
return state.showData.cities?.find((item)=>item.code === state.params.city)?.children
}) as any
// 监听省、市、地区的变化的变化
watch(()=>state.params.province, ()=>{
state.params.city = undefined
state.params.area = undefined
})
watch(()=>state.params.city, ()=>{
state.params.area = undefined
})
watch(()=>state.params.area, (val)=>{
// 区有值的时候,省市必定有值,此时就可以将数据返回给父组件
if(val){
// 组装数据
const paramsData = {
province: {} as areaType,
city: {} as areaType,
area: {} as areaType
}
let tmp = areaData.find((item) => item.code === state.params.province)
paramsData.province.name = tmp?.name as string
paramsData.province.code = tmp?.code as string
tmp = tmp?.children.find((item) => item.code === state.params.city) as any
paramsData.city.name = tmp?.name as string
paramsData.city.code = tmp?.code as string
tmp = tmp?.children.find((item) => item.code === state.params.area) as any
paramsData.area.name = tmp?.name as string
paramsData.area.code = tmp?.code as string
// 出触发父组件事件,传数据过去
emits('areaChange', paramsData)
}
})
以上便是省市区组件代码,欢迎大佬们批评指正!!
版权声明:本文为weixin_44832362原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。