npm安装
bash
npm install element-china-area-data -S
vue组件
创建addressCascader.vue文件
参数:
size: medium / small / mini
parameters: code/name(此处选中事件之后会将code、name都传)
bash
<template>
<div>
<el-cascader :size="size" :options="options" v-model="provinces" @change="dynamicHandleChange" :placeholder="placeholder"
:parameters="parameters"></el-cascader>
</div>
</template>
<script>
export default {
name: "addressCascader",
props: {
size: {
type: String,
default: "small", // 默认大小为small
},
options: {
type: Array,
default: () => [], // 默认选项数据为空数组
},
placeholder: {
type: String,
default: "请选择省市区", // 默认提示文字为"请选择省市区"
},
parameters: {
type: String,
default: "code", // 默认为code值
},
selectValue: {
type: String,
default: "",
},
},
data() {
return {
provinces: [], // 选中的省市区数据,默认为空数组
};
},
watch: {
selectValue: {
handler(newValue) {
// 确保选择框中的值已经更新完成
this.$nextTick(() => {
this.provinces = newValue.split("/");
});
},
immediate: true,
},
},
methods: {
dynamicHandleChange(e) {
//此处可根据parameters区分code/name
this.$emit("change", this.figure(e),this.ideograph(e));
},
// 传递中文数据
ideograph(code) {
const areas = [];
if (Array.isArray(code) && code.length) {
let region = this.options;
for (let i = 0; i < code.length; i++) {
const item = code[i];
const found = region.find((regionItem) => regionItem.value === item);
if (found) {
areas.push(found.label); // 直接将中文推入数组中
region = found.children || [];
if (i === code.length - 1) {
// 最后一个区域,可以打印或进行其他处理
}
} else {
break;
}
}
}
return areas.join("/");
},
// 传递code数据
figure(code) {
return code.join("/");
},
},
};
</script>
引用
bash
<template>
<div>
<cascader-component :selectValue="addr_code" :size="'medium'" :parameters="'code'" :options="regionData" :placeholder="'请选择城市'" @change="customChangeHandler">
</cascader-component>
</div>
</template>
<script>
import { regionData } from "element-china-area-data";
export default {
data() {
return {
regionData: regionData,
addr_code:''
};
},
methods: {
customChangeHandler(code,name) {
this.addr_code = code
},
},
};
</script>