vue-Treeselect实现组织机构(员工)下拉树的功能
知识点:前端使用vuetree的组件库,调用后台查询组织机构,包括人员的接口
实现下拉树的功能
查考:
vue-treeselect官网:https://vue-treeselect.js.org/
源码demo下载链接:https://github.com/shuaishuaihand/orgvuetreedemo.git
(一)效果:
(二)代码
1.后台接口(递归算法)
controller层
/**
* 查询组织结构下拉树
* @return
*/
@RequestMapping(value = "/findOrgUserTree", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public List<Map<String,Object>> findOrgUserTree() {
return orgService.findOrgUserTree(0);
}
service层
/**
* 递归查询组织机构-用户树节点
* @return
*/
public List<Map<String, Object>> findOrgUserTree(int pid) {
// 查找根节点
List<Map<String, Object>> list = orgMapper.findListByPid(pid);
List<Map<String, Object>> children;
for (Map<String, Object> m: list) {
children = findOrgUserTree((int)m.get("id"));
if (children != null && children.size() != 0) { //查询组织机构的子节点,并赋值给元素“children”
m.put("children",children);
} else {
children = userMapper.findUserByOrgId((int)m.get("id")); //当根节点组织结构时,查询结构下面的员工,并赋值给根节点组织机构的children
if (children != null && children.size() != 0) {
m.put("children",children);
}
//设置叶子组织机构(没有人员),为不可选 isDisabled为vuetree节点的属性,不能勾选
if(children == null ||children.size() == 0){
m.put("isDisabled",true);
}
}
}
return list;
}
mapper层
OrgMapper.xml:
<select id="findListByPid" resultType="java.util.HashMap" parameterType="java.lang.Integer">
select id,name as label from organization
<if test="pid!=0"> //pid为父节点的ID
WHERE PARENTID =#{pid}
</if>
<if test="pid==0">
WHERE (PARENTID < 1 or PARENTID is null)
</if>
</select>
组织机构表:
User.xml:
<select id="findUserByOrgId" resultType="java.util.HashMap">
select id ,user_name as label from user
<if test="orgId!=null">
WHERE ORG_ID =#{orgId} ORDER BY id
</if>
</select>
员工表:
后台查询的数组结果:
[{
"children": [{
"id": 602,
"label": "销售部",
"isDisabled": true
}, {
"children": [{
"id": 1851,
"label": "张三"
}, {
"id": 1852,
"label": "李四"
}],
"id": 603,
"label": "产品部"
}, {
"children": [{
"id": 1854,
"label": "李小萌"
}],
"id": 611,
"label": "研发部"
}],
"id": 1,
"label": "帅帅集团有限公司"
}]
2.前端组件(vue-treeselect)
<body> <!--:value-consists-of="valueConsistsOf"-->
<div id="app">
组织机构 //options1是后台接口传过来的数组; value作为绑定值,可以在修改时绑定ids数组;valueConsistsOf设定为叶子节点元素选择;
<treeselect :options="options1" :multiple="true" v-model="value" :value-consists-of="valueConsistsOf"
placeholder="选择成员"/>
</div>
<script>
// register the component
Vue.component('treeselect', VueTreeselect.Treeselect)
new Vue({
el: '#app',
data: {
// define default value
value: null,
valueConsistsOf: 'LEAF_PRIORITY',
// define options
options1: "",
},
//初始化方法
mounted:function () {
this.findZNodes();
},
methods: {
//加载修改树结构json
findZNodes: function () {
this.$http.post("/org/findOrgUserTree").then(function (response) {
this.options1 = response.data;
})
}
}
})
</script>
</body>