element-plus el-cascader 懒加载实现-省市区街道选择及回显

大概思路:

  1. 准备一个接口可以通过父Id,查询到下一级省市区街道的信息;如下方的getRegionListOne
  2. 确定后端的数据结构,需要在created里边处理数据回显逻辑
  3. el-cascader接收的数据格式是['','',''];后端的数据格式多为[{provinceId: '', regionId: '', cityId: ''}]
  4. 可以通过设置comType,来确定是省市区还是省市区街道,组件内完成逻辑处理。

直接上代码

js 复制代码
<template>
    <div class="areaLazy">
      <el-cascader
        v-model="currentChoose"
        v-bind="_options"
        :options="addressList"
        :disabled="_options.disabled"
        @change="handleChange"
      />
  </div>
</template>

<script>
export default {
  name: "addresscascaderlazy",
};
</script>

<script setup>
import { ref, computed, watch } from "vue";
import API from "@/api";

const emits = defineEmits([
  "update:modelValue"
]);

const props = defineProps({
  disabled: {
    //禁用
    type: Boolean,
    required: false,
    default: false,
  },
  options: {
    type: Object,
    default: () => {},
  },
  modelValue: {
    type: [Array, Object],
    default: () => ([]),
  },
});
let id = 0;
// 设置option默认值,如果传入自定义的配置则合并option配置项
const _options = computed(() => {
  const option = {
    name: "multipartFiles",
    comType: "provinceCityCountryRegion",
    props: {
      lazy: true,
      lazyLoad(node, resolve) {
        const { level, value } = node; // 获取当前node对象中的level, value属性
        getArea(level, value, resolve)
      },
    }
  };
  option.disabled = props.disabled;
  return Object.assign(option, props.options);
});
const levelTag = {
  "provinceCityCountryRegion": 3,
  "provinceCityCountry": 2,
  "provinceCity": 1,
}
const currentChoose = ref([]);
const addressList = ref([]);
const addressOrigin = ref({}); // 省市区数据

const handleChange = (val) => {
  console.log('handleChange', val)
  if (!val.length) {
    emits('update:modelValue', val)
    return
  }
  if (_options.value?.props?.multiple) {
    const arr = []
    val.forEach(item => {
      const obj = {}
      obj.provinceId = item[0]
      obj.provinceName = addressOrigin.value[0][item[0]]
      obj.cityId = item[1]
      obj.cityName = addressOrigin.value[1][item[1]]
      obj.regionId = item[2]
      obj.regionName = addressOrigin.value[2][item[2]]
      obj.streetId = val[3]
      obj.streetName = addressOrigin.value[3][val[3]]
      arr.push(obj)
    })
    emits('update:modelValue', arr)
  } else {
    const obj = {}
    obj.provinceId = val[0]
    obj.provinceName = addressOrigin.value[0][val[0]]
    obj.cityId = val[1]
    obj.cityName = addressOrigin.value[1][val[1]]
    obj.regionId = val[2]
    obj.regionName = addressOrigin.value[2][val[2]]
    obj.streetId = val[3]
    obj.streetName = addressOrigin.value[3][val[3]]
    emits('update:modelValue', obj)
  }
}

const getArea = (level, value, resolve) => {
  API.getRegionListOne({parentId: value}).then(async (res) => {
    addressOrigin.value[level] = {}
    const nodes = res.result.map(item => {
      addressOrigin.value[level][item.id] = item.name
      return {  
        value: String(item.id),
        label: item.name,
        leaf: level >= levelTag[_options.value?.comType],
      }
    })
    resolve(nodes)
  })
}

const created = () => {
  if (!props.modelValue) {
    return []
  }
  if (props.modelValue instanceof Array) {
    currentChoose.value = props.modelValue.map(item => {
      if (_options.value.comType === "provinceCityCountryRegion") {
        return [ item.provinceId, item.cityId, item.regionId, item.streetId ]
      }
      if (_options.value.comType === "provinceCityCountry") {
        return [ item.provinceId, item.cityId, item.regionId ]
      }
      return [ item.provinceId, item.cityId ]
    })
  } else {
    if (_options.value.comType === "provinceCityCountryRegion") {
      currentChoose.value = [props.modelValue.provinceId, props.modelValue.cityId, props.modelValue.regionId, props.modelValue.streetId]
      return
    }
    if (_options.value.comType === "provinceCityCountry") {
      currentChoose.value = [props.modelValue.provinceId, props.modelValue.cityId, props.modelValue.regionId, props.modelValue.streetId]
      return
    }
    currentChoose.value = [props.modelValue.provinceId, props.modelValue.cityId]
  }
}

// 省市区
// getaddressList();
watch(()=>props.modelValue, (val) => {
  created();
})

</script>

<style lang="less">
.areaLazy {
  .el-input__inner {
    min-width: 350px;
  }
}
</style>

再附一个非懒加载形式的

js 复制代码
<template>
    <div class="areaUnit">
      <el-cascader
        v-model="currentChoose"
        v-bind="_options"
        :options="addressList"
        :disabled="_options.disabled"
        @change="handleChange"
      />
  </div>
</template>

<script>
export default {
  name: "addresscascader",
};
</script>

<script setup>
import { ref, computed, watch } from "vue";
import API from "@/api";

const emits = defineEmits([
  "update:modelValue"
]);

const props = defineProps({
  disabled: {
    //禁用
    type: Boolean,
    required: false,
    default: false,
  },
  options: {
    type: Object,
    default: () => {},
  },
  modelValue: {
    type: [Array, Object],
    default: () => ([]),
  },
});

// 设置option默认值,如果传入自定义的配置则合并option配置项
const _options = computed(() => {
  const option = {
    name: "multipartFiles",
    comType: "provinceCityCountry",
  };
  option.disabled = props.disabled;
  return Object.assign(option, props.options);
});

const currentChoose = ref([]);
const addressList = ref([]);
const addressOrigin = ref({});
// 处理省市区数据结构
const handleBase = (list, childrenList, stringBan) => {
  return new Promise((resolve) => {
    const address = []
    if (childrenList) {
      for (const key in list) {
          const children = childrenList.filter(i => String(i.value).substring(0, stringBan) === String(key).substring(0, stringBan));
          address.push({
            value: key,
            label: list[key],
            children
          })
      }
    } else {
      for (const key in list) {
        address.push({
          value: key,
          label: list[key]
        })
      }
    }
    resolve(address)
  })
}

// 获取省市区
const getaddressList = () => {
  API.getRegionList().then(async (res) => {
    const { province_list, city_list, county_list } = res.result;
    addressOrigin.value = { province_list, city_list, county_list }
    if (_options.value.comType === "provinceCityCountry") {
      const countyAddress = await handleBase(county_list)
      const cityAddress = await handleBase(city_list, countyAddress, 4)
      addressList.value = await handleBase(province_list, cityAddress, 2)
    }
    if (_options.value.comType === "provinceCity") {
      const cityAddress = await handleBase(city_list)
      addressList.value = await handleBase(province_list, cityAddress, 2)
    }
  })
}
const handleChange = (val) => {
  if (!val.length) {
    emits('update:modelValue', val)
    return
  }
  if (_options.value?.props?.multiple) {
    const arr = []
    val.forEach(item => {
      const obj = {}
      obj.provinceId = item[0]
      obj.provinceName = addressOrigin.value.province_list[item[0]]
      obj.cityId = item[1]
      obj.cityName = addressOrigin.value.city_list[item[1]]
      obj.regionId = item[2]
      obj.regionName = addressOrigin.value.county_list[item[2]]
      arr.push(obj)
    })
    emits('update:modelValue', arr)
  } else {
    const obj = {}
    obj.provinceId = val[0]
    obj.provinceName = addressOrigin.value.province_list[val[0]]
    obj.cityId = val[1]
    obj.cityName = addressOrigin.value.city_list[val[1]]
    obj.regionId = val[2]
    obj.regionName = addressOrigin.value.county_list[val[2]]
    emits('update:modelValue', obj)
  }
}

const created = () => {
  if (!props.modelValue) {
    return []
  }
  if (props.modelValue instanceof Array) {
    currentChoose.value = props.modelValue.map(item => {
      if (_options.value.comType === "provinceCityCountry") {
        return [ item.provinceId, item.cityId, item.regionId ]
      }
      return [ item.provinceId, item.cityId ]
    })
  } else {
    if (_options.value.comType === "provinceCityCountry") {
      currentChoose.value = [props.modelValue.provinceId, props.modelValue.cityId, props.modelValue.regionId]
    } else {
      currentChoose.value = [props.modelValue.provinceId, props.modelValue.cityId]
    }
  }
}

// 省市区
getaddressList();
watch(()=>props.modelValue, (val) => {
  console.log('modelValue', val)
  created();
})
</script>
相关推荐
EasyNTS24 分钟前
H.264/H.265播放器EasyPlayer.js视频流媒体播放器关于websocket1006的异常断连
javascript·h.265·h.264
活宝小娜2 小时前
vue不刷新浏览器更新页面的方法
前端·javascript·vue.js
程序视点2 小时前
【Vue3新工具】Pinia.js:提升开发效率,更轻量、更高效的状态管理方案!
前端·javascript·vue.js·typescript·vue·ecmascript
coldriversnow2 小时前
在Vue中,vue document.onkeydown 无效
前端·javascript·vue.js
我开心就好o2 小时前
uniapp点左上角返回键, 重复来回跳转的问题 解决方案
前端·javascript·uni-app
开心工作室_kaic3 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
刚刚好ā3 小时前
js作用域超全介绍--全局作用域、局部作用、块级作用域
前端·javascript·vue.js·vue
沉默璇年4 小时前
react中useMemo的使用场景
前端·react.js·前端框架
yqcoder4 小时前
reactflow 中 useNodesState 模块作用
开发语言·前端·javascript
2401_882727574 小时前
BY组态-低代码web可视化组件
前端·后端·物联网·低代码·数学建模·前端框架