<template>
<div class="xtx-city" ref="target">
<div class="select" @click="toggleDialog" :class="{ active }">
<span class="placeholder" v-if="!seled.fullSels">请选择配送地址</span>
<span class="value" v-else>{{ seled.fullSels }}</span>
<i class="iconfont icon-angle-down"></i>
</div>
<div class="option" v-if="active">
<span
class="ellipsis"
@click="selCity(city)"
v-for="city in cityList"
:key="city.code"
>{{ city.name }}</span
>
</div>
</div>
</template>
<script>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { onClickOutside } from '@vueuse/core'
function useCityList () {
const cityList = ref([])
const backupCityList = []
const getCityList = async () => {
const { data } = await axios({ url: 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json' })
console.log('citys:', data)
backupCityList.push(...data)
cityList.value = data
}
onMounted(() => {
getCityList()
})
return { cityList, backupCityList }
}
export default {
name: 'XtxCity',
emits: ['change'],
setup (props, { emit }) {
const { cityList, backupCityList } = useCityList()
const target = ref()
const active = ref(false)
function open () {
console.log(backupCityList)
cityList.value = backupCityList
active.value = true
}
function close () {
active.value = false
}
onClickOutside(target, () => close())
function toggleDialog () {
if (active.value) {
close()
} else {
open()
}
}
const seled = reactive({
provinceCode: '',
provinceName: '',
cityCode: '',
cityName: '',
countryCode: '',
countryName: '',
fullSels: ''
})
const selCity = (currCity) => {
console.log(currCity)
cityList.value = currCity.areaList
if (currCity.level === 0) {
seled.provinceName = currCity.name
seled.provinceCode = currCity.code
} else if (currCity.level === 1) {
seled.cityName = currCity.name
seled.cityCode = currCity.code
} else {
seled.countryName = currCity.name
seled.countryCode = currCity.code
seled.fullSels = seled.provinceName + ' ' + seled.cityName + ' ' + seled.countryName
toggleDialog()
emit('change', seled)
}
}
return { active, toggleDialog, cityList, selCity, seled, target }
}
}
</script>
<style scoped lang="less">
.xtx-city {
display: inline-block;
position: relative;
z-index: 400;
margin-left: 10px;
.select {
border: 1px solid #e4e4e4;
height: 30px;
padding: 0 5px;
line-height: 28px;
cursor: pointer;
&.active {
background: #fff;
}
.placeholder {
color: #999;
}
.value {
color: #666;
font-size: 12px;
}
i {
font-size: 12px;
margin-left: 5px;
}
}
.option {
width: 542px;
border: 1px solid #e4e4e4;
position: absolute;
left: 0;
top: 29px;
background: #fff;
min-height: 30px;
line-height: 30px;
display: flex;
flex-wrap: wrap;
padding: 10px;
> span {
width: 130px;
text-align: center;
cursor: pointer;
border-radius: 4px;
padding: 0 3px;
&:hover {
background: #f5f5f5;
}
}
}
}
</style>