此篇文章主要讲如何获取地址的方法。因为地址的json地址文件太大,如提供的地址文件不是json格式的话,可以直接在线转换,这里不就作展示,会在下面代码里用到的地方截图展示。
项目环境:项目环境:vue + vue-cli + element-ui
最终效果图:

1、布局
<template>
<el-form :label-position="labelPosition" label-width="130px" :model="formLabelPay">
<el-form-item label="Billing address:" prop="baddress">
<el-select v-model="formLabelPay.country" placeholder="Country" style="width: 20%" @visible-change="chooseCountry($event)">
<el-option v-for="item in countryList" :key=item.name :label=item.name :value=item.code @click.native="clickCountry(item)"></el-option>
</el-select>
<el-select v-model="formLabelPay.state" placeholder="State" style="width: 20%" @visible-change="chooseState($event)">
<el-option v-for="item in stateList" :key=item.name :label=item.name :value=item.code @click.native="clickState(item)"></el-option>
</el-select>
<el-select v-model="formLabelPay.city" placeholder="City" style="width: 20%" @change="clickCity($event)" @visible-change="chooseCity($event) ">
<el-option v-for="item in cityList" :key=item.name :label=item.name :value=item.code @click.native="clickCity(item)"></el-option>
</el-select>
</el-form-item>
<el-form-item label="Detailed address:" prop="address">
<el-input v-model="formLabelPay.address" onkeyup="value=value.replace(/[\u4E00-\u9FA5]/g,'')" style="width: 61%"></el-input>
</el-form-item>
</el-form-item>
</el-form>
</<template>>
3、代码
// 代码中 注释的地方是另外一种写法,就是必须要按国家-市-区顺序来获取的,供参考
<script>
// 引入国家/州/城市地址 api
import { getAddress } from '@/api/api'
export default {
data () {
return {
countryList: [],
stateList: [],
cityList: [],
// 对象
country: '',
// 对象
state: '',
// 对象
city: '',
}
},
methods: {
// 获取到所有国家
chooseCountry ($event) {
if ($event === true) {
this.countryList = getAddress() // 见下图片
}
},
// 点击选中国家时,判断是否存在州,如果不存在,则判断是否存在城市,存在则获取,不存在则清空
clickCountry (item) {
console.log(item) // 打印出来是整个国家的信息(打印出来是一个对象)
this.country = item // 把整个国家的信息赋值给
this.stateList = []
this.cityList = []
if (this.country.State instanceof Array) {
this.stateList = this.country.State
} else if (this.country.State && this.country.State.City instanceof Array) {
this.cityList = this.country.State.City
}
// 每重新选择一次地址,相对应的州和城市都被清空
this.formLabelPay.stateCode = ''
this.formLabelPay.cityCode = ''
},
chooseState ($event) {
// if ($event === true) {
// if (this.country.State instanceof Array) {
// this.stateList = this.country.State
// } else {
// this.cityList = this.country.State.City
// }
// }
},
clickState (item) {
console.log(item)
this.state = item
// 选中州以后,判断是否存在市,存在则获取
if (this.state.City instanceof Array) {
this.cityList = this.state.City
}
},
chooseCity ($event) {
// if ($event === true) {
// if (this.state.City instanceof Array) {
// this.cityList = this.state.City
// }
// }
},
clickCity (item) {
// console.log(item)
// console.log(this.formLabelPay.countryCode)
// console.log(this.formLabelPay.stateCode)
// console.log(this.formLabelPay.cityCode)
this.city = item
}
}
}
</script>

网友评论