封装一个省市区公共组件

难点:封装一个省市区三级联动的公共组件,难点在与对三级嵌套数据的处理,其中三级嵌套数据来源于github上的Administrative-divisions-of-china

<template>
	<el-select v-model="province" class="m-2" placeholder="请选择省份" size="small">
	  <el-option
		v-for="item in areas"
		:key="item.code"
		:label="item.name"
		:value="item.code"
	  />
	</el-select>
	<el-select v-model="city" :disabled="!province" class="m-2" placeholder="请选择市" size="small">
	  <el-option
		v-for="item in selectCitys"
		:key="item.code"
		:label="item.name"
		:value="item.code"
	  />
	</el-select>
	<el-select v-model="area" :disabled="!city" class="m-2" placeholder="请选择区" size="small">
	  <el-option
		v-for="item in selectAreas"
		:key="item.code"
		:label="item.name"
		:value="item.code"
	  />
	</el-select>
  </template>
  
  <script setup>
  import { ref, watch, defineEmits } from 'vue'
  import allAreas from './lib/pca-code.json'
  
  const areas = ref(allAreas)
  const selectCitys = ref([])
  const selectAreas = ref([])
  const province = ref('')
  const city = ref('')
  const area = ref('')
  const emit = defineEmits(['change'])

  watch(province,async (value) => {
	if(value) {
		let citys = areas.value.find(item => 
			item.code===province.value
		)?.children
		selectCitys.value = citys
		city.value = ''
		area.value = ''
	}else{
		return
	}
  })
  
  watch(city,async (value) => {
	if(value) {
		let areas = selectCitys.value.find(item => 
			item.code===city.value
		)?.children
		selectAreas.value = areas
		area.value = ''
	}else{
		return
	}
  })

  watch(area,async (value) => {
	if(value) {
		let provinceData = {
			code: province.value,
			name: areas.value.find(item => item.code===province.value)?.name,
		}
		let cityData = {
			code: city.value,
			name: selectCitys.value.find(item => item.code===city.value)?.name,
		}
		let areaData = {
			code: area.value,
			name: selectAreas.value.find(item => item.code===area.value)?.name
		}
		emit('change',{
			provinceData,
			cityData,
			areaData
		})
	}
  })


  </script>
  

你可能感兴趣的:(javascript,开发语言,ecmascript)