vue3实现省市区三级联动

 效果图

 注:option的样式不能用CSS修改,可以换成ul li

            
            
            
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;
      }

想要数据的可以私我

你可能感兴趣的:(javascript,前端,vue.js)