Element-Cascader 级联选择器-基础用法-基于Spring Cloud
需求
- 前端需求:以级联选择器的模式,逐级选择数据。
- 数据要求:从数据库中的获取树形结构数据
思路
Element-Cascader 的使用方式基本上包括两种,一种是一次性将Cascader需要展现的所有数据全部获取,并且提交给Cascader。
另外一种,就是根据需要实时去数据库或者其他数据源上提取需要的数据,并且提交给Cascader。
当然从效果上来说,肯定第二种比较好。但是今天描述的是第一种(为啥呢?不直接使用更好的? 我是不会告诉你的,我第二种还没有彻底搞清楚的 zZZ )
方法
后端
Cascader 对数据格式的要求:
{
value: 'zhinan',
label: '指南',
children: [{
value: 'shejiyuanze',
label: '设计原则',
children: [{
value: 'yizhi',
label: '一致'
}, {
value: 'fankui',
label: '反馈'
}, {
value: 'xiaolv',
label: '效率'
}, {
value: 'kekong',
label: '可控'
}]
}, {
value: 'daohang',
label: '导航',
children: [{
value: 'cexiangdaohang',
label: '侧向导航'
}, {
value: 'dingbudaohang',
label: '顶部导航'
}]
}]
},
所以第一个需要去数据库或者其他数据源中,将需要的数据按照格式要求提出出来.直接上代码吧。
Mapper.xml 文件中新增一个SQL语句:
<select id="selectYSystemDictLikeAncestors" parameterType="String" resultMap="YSystemDictResult">
<include refid="selectYSystemDictVo"/>
where ancestors like CONCAT('%',#{ancestors},'%')
</select>
mapper,service 中增加方法:
public List<YSystemDict> selectYSystemDictLikeAncestors(String ancestors);
controller中增加方法:
@GetMapping("/getSystemDictTreeByAncestors/{dictId}")
public AjaxResult getSystemDictTreeByAncestors(@PathVariable("dictId") Long dictId) {
String ancestors = "," + dictId;
List<YSystemDict> list = ySystemDictService.selectYSystemDictLikeAncestors(ancestors);
List<Map<String,Object>> systemDictTreeList = systemDictTreeHandle(list, dictId);
return AjaxResult.success(systemDictTreeList);
}
private List<Map<String,Object>> systemDictTreeHandle(List<YSystemDict> ySystemDictList, long pId) {
List<Map<String,Object>> resultList = new ArrayList<>();
//获取元素集合
long parentId;
for (YSystemDict ySystemDict : ySystemDictList) {
parentId = ySystemDict.getParentId();
if (pId == parentId) {
Map map = new HashMap();
map.put("value", ySystemDict.getDictId());
map.put("label", ySystemDict.getDictValue());
resultList.add(map);
}
}
//获取元素的子数据
for (Map map : resultList) {
long value = Long.parseLong(map.get("value").toString());
List<Map<String,Object>> temp = systemDictTreeHandle(ySystemDictList, value);
if (temp.size() > 0) {
map.put("children", temp);
}
}
return resultList;
}
前端:
api:
// 获取业务字典树形数据
export function getSystemDictTreeByAncestors(parentId) {
return request({
url: '/xx/systemdict/getSystemDictTreeByAncestors/' + parentId,
method: 'get'
})
}
vue:
引用这个函数:
import { getSystemDictTreeByAncestors } from "@/api/XX/systemdict";
下拉框:
<el-form-item label="所属项目" prop="projectDesc">
<el-cascader v-model="form.projectDesc" :options="projectDescOptions" :props="projectDescProps"
placeholder="请选择所属项目" clearable></el-cascader>
</el-form-item>
