对于省市区级联选择,很多做法都是通过一级一级的调用服务端接口来实现的,今天介绍一个完全采用前端、基于Ant Design Vue来构建的省市区级联选择组件。
一、准备省市区数据
1.下载省市区数据
省市区JSON数据
2.将省市区数据保存到areadata.js文件中,并导出
//地区json数据
export default [
{
code: "11",
name: "北京市",
children: [
{
code: "1101",
name: "市辖区",
children: [
{
code: "110101",
name: "东城区"
},
{
code: "110102",
name: "西城区"
...
二、基于Cascader包装成省市区组件
<template>
<a-cascader
:fieldNames="{ label: 'name', value: 'code', children: 'children' }"
:options="areaData"
:placeholder="placeholder"
v-model="selectedValues"
@change="onChange"
/>
</template>
<script>
import areaData from "./areadata";
export default {
name: "areaSelect",
props: {
placeholder: {
type: String,
default: "请选择省市区",
},
defaultValue: {
type: Array,
default() {
return [];
},
},
},
data() {
return {
//地区数据
areaData,
//选择的数据
selectedValues: [],
};
},
created() {
if (this.defaultValue.length) {
this.selectedValues = [...this.defaultValue];
}
},
watch: {
defaultValue(newValue) {
if (newValue.length) {
this.selectedValues = newValue;
} else {
this.selectedValues = [];
}
},
},
methods: {
//选择好之后的回调
onChange(value) {
this.$emit("change", value);
},
},
};
</script>
<style lang="scss" scoped>
</style>
三、使用该组件
<template>
<div>
<!-- 省市区选择器 -->
<area-select
@change="selectArea"
:default-value="defaultArea"
/>
</div>
</template>
<script>
//导入构建好的组件
import areaSelect from "./areaselect";
export default {
components: {
areaSelect,
},
data() {
return {
//配置默认选中的省市区(依次是省市区的区域代码)
defaultArea:['32','3205','320571'],
};
},
methods: {
//选择地区之后的回调
selectArea(selectedArea) {
console.log(selectedArea);
},
},
};
</script>
<style lang="scss" scoped>
</style>