123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <template>
- <el-cascader
- :key="cascaderKey"
- v-model="internalValue"
- placeholder="请选择地址.."
- :props="SearchCityData"
- filterable
- clearable
- @change="handleChange">
- </el-cascader>
- </template>
- <script>
- export default {
- props: {
- value: { // 接收外部传递的 v-model 值
- type: [Array, String], // 允许传入数组或字符串类型的数据
- default: () => [],
- },
- },
- data() {
- let self = this;
- return {
- internalValue: [], // 用于与级联选择器进行双向绑定的内部数据
- cascaderKey: 0, // 用于强制刷新 cascader
- SearchCityData: {
- checkStrictly: true,
- lazy: true,
- async lazyLoad(node, resolve) {
- const { level, data } = node;
- let parentId = level == 0 ? 0 : data.value;
- let parames = {
- pid: parentId,
- };
- self.$store
- .dispatch("pool/getcityList", parames)
- .then((res) => {
- if (res.data) {
- const nodes = res.data.map((item) => ({
- value: item.id,
- label: item.name,
- leaf: level >= 3,
- children: [],
- }));
- resolve(nodes);
- }
- })
- .catch(() => {
- this.$message({
- type: "info",
- message: "网络错误,请重试!",
- });
- });
- },
- },
- };
- },
- watch: {
- value: {
- immediate: true, // 组件挂载时立即执行
- handler(newVal) {
- try {
- const parsedValue = Array.isArray(newVal) ? newVal : JSON.parse(newVal);
- this.internalValue = parsedValue; // 设置内部值
- if (parsedValue.length) {
- this.loadCascaderPath(parsedValue); // 动态加载回显的路径
- }
- } catch (error) {
- console.error("无法解析传入的值:", error);
- this.internalValue = []; // 如果解析失败,重置为默认空数组
- }
- },
- },
- },
- methods: {
- handleChange(value) {
- // 当选择变化时,向父组件发送更新的值
- this.$emit("input", value); // v-model 双向绑定
- this.$emit("update-city-id", value); // 额外事件,方便父组件监听
- },
- async loadCascaderPath(path) {
- for (let i = 0; i < path.length; i++) {
- const parentId = path[i - 1] || 0; // 获取当前层级的父级ID
- const level = i; // 当前层级的索引
- await this.$store.dispatch('pool/getcityList', { pid: parentId })
- .then((res) => {
- const nodes = res.data.map(item => ({
- value: item.id,
- label: item.name,
- leaf: level >= 3, // 假设4层结构,设置叶子节点标记
- }));
- // 级联选择器加载数据
- if (level === path.length - 1) {
- this.internalValue = path; // 确保最后一级路径正确设置
- this.cascaderKey += 1; // 强制刷新 cascader
- }
- });
- }
- },
- },
- };
- </script>
- <style scoped>
- /* 可根据需要自定义样式 */
- </style>
|