Vue el-cascader级联进行懒加载功能实现
话不多说直接看代码
动态加载
当选中某一级时,动态加载该级下的选项:
通过lazy开启动态加载,并通过lazyload来设置加载数据源的方法。 lazyload方法有两个参数,第一个参数node为当前点击的节点,第二个resolve为数据加载完成的回调(必须调用)。 为了更准确的显示节点的状态,还可以对节点数据添加是否为叶子节点的标志位 (默认字段为leaf,可通过props.leaf修改)。 否则,将以有无子节点来判断其是否为叶子节点。
示例:
<template>
<el-cascader :props="props" />
</template>
<script lang="ts" setup>
import type { CascaderProps } from 'element-plus'
let id = 0
const props: CascaderProps = {
lazy: true,
lazyLoad(node, resolve) {
const { level } = node
setTimeout(() => {
const nodes = Array.from({ length: level + 1 }).map((item) => ({
value: ++id,
label: `Option - ${id}`,
leaf: level >= 2,
}))
// Invoke `resolve` callback to return the child nodes data and indicate the loading is finished.
resolve(nodes)
}, 1000)
},
}
</script>
实际操作:
<template>
<div>
<el-cascader
style="width: 100%; height: 30px; padding: 0px; line-height: 35px; font-size: 14px;"
ref="cascaderRef"
placeholder="请选择行政区域"
v-model="Materialform.RegionalismId"
:options="options"
:props="props"
></el-cascader>
</div>
</template>
data(){
Materialform:{
RegionalismId:[],
},
props: {
value: 'value',
label: 'label',
expandTrigger: 'hover',
lazy: true,
lazyLoad: this.lazyLoad
},
isModify: false, // 标识当前是新增还是修改操作
options: [],
created() {
this.loadInitialOptions()
},
// 加载第一级选项
loadInitialOptions() {
try {
let that = this;
that.options = [];
that.http.ajax2({url: "/api/regions",
postdata: true,
success: function (result) {
if (result.Status) {
that.options = result.Data.map(x => {
return {
value: x.Id,
label: x.Ext_Name,
parentId: x.PId,
leaf: false,
children: []
};
});
}
},
type: "post",
async: false
});
return that.options;
} catch (error) {
console.error('加载初始选项失败:', error);
}
},
lazyLoad(node, resolve) {
try {
const { level, data } = node;
if (level > 0) {
const url = `/api/regions?pId=${data.value}`;
this.http.post(url, null, "加载中").then(result => {
if (result.Status) {
const children = result.Data.map(x => {
return {
leaf: level >= 4,
value: x.Id,
label: x.Ext_Name,
parentId: x.PId,
children: []
};
});
// 将子节点数据添加到当前节点的 children 属性中
data.children = children;
resolve(children);
}
});
}
} catch (error) {
console.error('加载子节点数据失败:', error);
resolve([]);
}
},
// 新增操作
handleAdd() {
this.isModify = false;
this.selectedValues = [];
},
// 修改操作
async handleModify() {
this.isModify = true;
await this.loadOptionsForExistingValues();
this.selectedValues = this.existingValues;
},
// 根据已有值加载选项
loadOptionsForExistingValues() {
let currentOptions = this.options;
for (let i = 0; i < this.Materialform.RegionalismId.split(',').length; i++) {
const value = Number(this.Materialform.RegionalismId.split(',')[i]);
const node = currentOptions.find(option => option.value === value);
if (node) {
if (i < this.Materialform.RegionalismId.split(',').length - 1) {
if (!node.children || node.children.length === 0) {
this.loadChildren(node);
}
currentOptions = node.children;
}
}
}
},
// 加载子节点
loadChildren(node) {
try {
console.log("1")
const url = `//api/regions?pId=${node.value}`;
this.http.post(url, null, "加载中").then(reslut => {
if (reslut.Status) {
let children = reslut.Data.map(x => {
return {
value: x.Id,
label: x.Ext_Name,
parentId: x.PId,
};
})
node.children = children;
//node.Data.children = children;
//resolve(children);
}
})
} catch (error) {
console.error('加载子节点失败:', error);
}
},
后台代码:
//控制器
[HttpPost, Route("*名称*")]
public async Task<IActionResult> *名称*(int pId = 0)
{
return JsonNormal(data: await Service.*名称*(pId));
}
//写在IService
Task<WebResponseContent> *名称*(int pId = 0);
//--写在Service
/// <summary>
/// 懒加载树
/// </summary>
/// <param name="pId">父级Id</param>
/// <returns></returns>
public async Task<WebResponseContent> *名称*(int pId = 0)
{
var list = await _repository.FindAsIQueryable(a => 根据上级ID判断).Select(a => new {字段}).ToListAsync();
return _webResponse.OK(data: list);
}
代码解释:
- created 钩子:在组件创建时调用 loadInitialOptions 方法,加载第一级的选项数据。
- handleAdd 方法:处理新增操作,将 isModify 设为 false,并清空 selectedValues。
- handleModify 方法:处理修改操作,将 isModify 设为 true,调用 loadOptionsForExistingValues 方法加载与已有值对应的选项,最后把 existingValues 赋给 selectedValues。
- loadOptionsForExistingValues 方法:遍历 existingValues,根据每个值找到对应的节点,若该节点的子节点未加载,则调用 loadChildren 方法加载子节点。
- lazyLoad 方法:当用户展开节点时,动态加载子节点数据。
- loadChildren 方法:根据节点的 value 加载其子节点数据。
–那位大佬会动态选择层级,请教教我,
题目为:如果级联下级只存在一级则选择一级,如果级联下级存在四级则可以选择四级