背景:
项目:XX管理系统
前端:iview-admin
后端:netcore
模块:用户管理
功能:部门菜单
组件:select
数据源:部门表(字段:当前部门id,父部门id)
需求:
可以向前选择部门
向后退回上一级部门
初始化为根部门
实现方案:
select的onchange事件绑定方法:以当前部门id为参数向后端请求所有一级子部门的部门集 合,并重新赋值select option属性的v-for 对象,如果集合为空则不赋值(向前选择部门)
select的onclear事件绑定方法:向后端请求以根部门为元素的部门源并重新赋值select option属性的v-for 对象(初始化为跟部门)
修改select的header为向左箭头图标并把header的onclick属性重新绑定方法:以当前部门id 为参数向后端请求当前部门的爷爷节点为父节点的部门集合,并标注选定节点为当前部门 的父部门,并重新赋值select option属性的v-for为部门集合和v-model对象为被标注的部门
(向后退回上一级部门)
代码:
1select组件
<Select v-model="pagedList.whereDom.PartityId"
style="width: 10%"
filterable
clearable
placeholder="部门"
prefix="md-arrow-back"//自定义向左箭头
:label-in-value="true"
@on-clear="initPartity"//初始化部门
@on-change="forwardParitySelect">//向前选择部门
<Option
v-for="item in PartityIdList"
:value="item.OrgId"
:key="item.Id">{{ item.PartityName }}</Option>
</Select>
向前选择方法
methods: {
// 向前选择部门
forwardParitySelect(e) {
if (e !== undefined) {
// 后端请求
forwardParitySearch({ id: e.value }).then((res) => {
if (res.data.length > 0) {
debugger;
//此处的赋值是为搜索方法提供参数,因为在重新赋值后 this.pagedList.whereDom.PartityId的值就会被清空所以不能以select的当前选项作为搜索参数
this.seconderyPartityId = this.pagedList.whereDom.PartityId;
this.PartityIdList = res.data;
} else {
this.seconderyPartityId = this.pagedList.whereDom.PartityId;
}
});
}
},
...
向前选择较为简单,需要注意的是要校验当前选择项是否为undefined否则会产生二次请求(因为重新赋option的v-for源时会再次触发onchange方法
初始化部门方法
methods: {
...
//初始化部门
initPartity() {
//后端方法
initPartity().then((res) => {
if (res.data.length > 0) {
debugger;
//此处的赋值是为搜索方法提供参数,
this.seconderyPartityId = this.pagedList.whereDom.PartityId;
this.PartityIdList = res.data;
}
});
},
...
向后退回上一级部门
此方法最不好实现,原因有二
第一要修改selectheader的默认click事件
第二要阻止的prefix(slot)click方法向上冒泡
实现代码:
//修改selecheader的click事件
mounted() {
debugger;
var item2 = document.querySelectorAll(".ivu-icon-md-arrow-back");
item2[0].onclick = this.backwardParitySelect;
},
methods: {
...
//后退方法
backwardParitySelect(e) {
debugger;
if (this.pagedList.whereDom.PartityId == undefined &&this.PartityIdList
[0].PartityName=== "根部门名称")
return
if (
this.pagedList.whereDom.PartityId === "" ||
this.pagedList.whereDom.PartityId === undefined
) {
this.pagedList.whereDom.PartityId = this.PartityIdList[0].OrgId;
}
//阻止冒泡
e.cancelBubble = true;
//后端方法
backPartitySearch({ id: this.pagedList.whereDom.PartityId }).then(
(res) => {
var selectflag = false;
this.PartityIdList = res.data;
this.PartityIdList.forEach((value) => {
if (value.IsSelected === true) {
this.pagedList.whereDom.PartityId = value.OrgId;
this.seconderyPartityId = value.OrgId;
selectflag = true;
}
});
if (selectflag === false) {
this.seconderyPartityId = null;
}
// this.search()
}
);
...