效果图
注:option的样式不能用CSS修改,可以换成ul li
<select @change="handleProvinceChange">
<option value="">请选择 — 省</option>
<option
v-for="(info,provinceName) in provinces"
:value="`${info.code}:${provinceName}`"
>{{ provinceName }}</option>
</select>
<select @change="handleCityChange"
v-if="isCitySelectorShow">
<option value="">请选择 — 市</option>
<option
v-for="(info,cityName) in state.cities"
:value="`${info.code}:${cityName}`"
>{{ cityName }}</option>
</select>
<select @change="handleCountryChange"
v-if="iscountrySelectorShow">
<option value="">请选择 — 区</option>
<option
v-for="(info,countryName) in state.counties"
:value="`${info.code}:${countryName}`"
>{{ countryName }}</option>
</select>
import cityData from '../home/city' //cityData是全国省市区数据
import { reactive,ref,computed ,toRaw} from 'vue';
var provinces = reactive('')
const isCitySelectorShow = computed(()=>!!state.cities) //第一个!转化为布尔值,第二个!取反
const iscountrySelectorShow = computed(()=>!!state.counties)
const state = reactive({
cities:null,
counties:null,
selectedInfo:{
province:null,
city:null,
country:null
}
})
const handleProvinceChange = (e)=>{
const {value} = e.target
if(!value) {
state.cities = null
state.counties = null
state.selectedInfo.province = null
state.selectedInfo.city = null
state.selectedInfo.country = null
return
}
const [code,name] = value.split(':');
state.selectedInfo.province = {
code,
name
},
console.log( provinces[name],'111');
state.cities = provinces[name].children
}
const handleCityChange = (e)=>{
const {value} = e.target
if(!value){
state.counties = null
state.selectedInfo.city = null
state.selectedInfo.country = null
return
}
const [code,name] = value.split(':');
state.selectedInfo.city = {
code,
name
},
console.log(name,'333');
state.counties = state.cities[name].children
}
const handleCountryChange = (e)=>{
const {value} = e.target
if(!value){
state.selectedInfo.country = null
state.counties = null
return
}
const [code,name] = value.split(':');
state.selectedInfo.country = {
code,
name
}
console.log(toRaw(state.selectedInfo));
}
const formData = (data)=>{ //改变数据结构,将name放在前面,便于获取
return data.reduce((prev1,next1)=>{
if(next1.children.length >=1){
next1.children = next1.children.reduce((prev2,next2)=>{
next2.children = next2.children.reduce((prev3,next3)=>{
prev3[next3.value] = next3
return prev3
},{})
prev2[next2.value] = next2
return prev2
},{})
}
prev1[next1.value] = next1
return prev1
},{})
}
provinces = formData(cityData)
select {
height: 35px;
width: 150px;
border: 1px solid #e5e5e5;
border-radius: 8px;
outline: none; /*清除难看的粗黑线*/
padding: 4px 10px 4px 10px;
font-size: 14px;
margin-left: 10px;
}
option {
color: rgb(88, 88, 88);
margin-bottom: 20px;
}
想要数据的可以私我
版权声明:本文为weixin_61891798原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。