仅以此文 纪念我无声的三周年司龄 以及2019年8月 姿美堂709的封闭开发时光!!!

 

每年的八月份都是我司封闭开发的 大(ku)好(bi)时光,今年封闭开发带着我的小团队用iview-admin2重新构建了app后台管理系统

期间产品需求有树形控件 - 单选 需求,旧后台用的zTree 自带此功能 无需多说,换成iview居然没有单选,只有多选

百度之~

恩 要是一下就查到解决方案 也就不会有这篇文章了

既然度娘没给 我就做第一个吧!!!

成品图如下:

<Tree class="ml20 radioTree"

show-checkbox

ref="tree"

:check-strictly='true'

:data="amendTreeData"   

@on-check-change='changeCheck'  ></Tree>

tree数据是跟后台协定好的

贴一段自行配置树展开所有节点的遍历代码 如有需要 自取就好

//展开或合并树,当flag为true时全部展开,flag为false时全部合并

exchangeTree(flag) {

this.amendTreeData = this.treeChangeExpand(this.amendTreeData, flag);

},

//递归给树设置expand

treeChangeExpand(treeData, flag) {

let _this = this;

for (var i = 0; treeData && i < treeData.length; i++) {

this.$set(treeData[i], 'expand', flag); //重要!用set方法

if (treeData[i].children) {

treeData[i].children = _this.treeChangeExpand(treeData[i].children, flag);

}

}

return treeData;

},

展开后样式如下:

show-checkbox 为开启多选框

@on-check-change='changeCheck'  为用户选中多选框的回调函数 会返还当前选中的节点数据集合 [{ 1节点数据 },{ 2节点数据 }]

还有个selected属性会给你点击选中的节点加上灰色背景

当时大概思路就是 既然每次选中会返还一个数组 始终保持数组里只有一个元素有checked属性为true不就是单选了么

改造上面的函数 新增为

selectedTree(id, flag) {

this.amendTreeData = this.treeChangeSelected(this.amendTreeData, id, flag);

},

treeChangeSelected(treeData, Id, flag) {

let _this = this;

for (var i = 0; treeData && i < treeData.length; i++) {

this.$set(treeData[i], 'selected', false); //重要!用set方法

if (Id !== treeData[i].id) { //非当前选中设置为未选中

this.$set(treeData[i], 'checked', flag); //重要!用set方法

} else {

this.$set(treeData[i], 'checked', !flag);

}

if (treeData[i].children) {

treeData[i].children = _this.treeChangeSelected(treeData[i].children, Id, flag);

}

}

return treeData;

},

以上为单选功能实现核心代码 且能去除所有节点的selected状态!

值得一说的是 选中后会返还两个参数 你要在回调用筛选出当前选中的元素 和 上次选中的元素

然后找到当前的那个元素的id后使用

this.selectedTree(this.checkId, false)

将这个唯一的id对应节点赋值checked:true  其他皆为false即可

此处坑比较深 因为它数据虽然只有两个 但新的数据有可能在第一个 也有可能在第二个 调BUG调了好久 采用中转数据才解决这问题

贴下代码吧!

changeCheck(res) { //单选封装

if (res.length == 0) {

this.checkId = '';

this.checkArr = [];

} else if (res.length == 1) {

this.checkId = res[0].id;

this.checkArr = res[0];

} else if (res.length > 1) {

// 需获取与当前缓存不一样的id 赋值到新的id里

if (this.checkId === '') {

if (this.parent.pid === res[0].id) {

this.checkId = res[1].id;

this.checkArr = res[1];

} else {

this.checkId = res[0].id;

this.checkArr = res[0];

}

} else if (res[0].id === this.checkId) {

this.checkId = res[1].id;

this.checkArr = res[1];

} else {

this.checkId = res[0].id;

this.checkArr = res[0];

}

this.selectedTree(this.checkId, false)

}

},

以上Js功能已实现项目需求 图片如下:

就差css样式了

赠送一个css深度选择器吧!

即 /deep/ 和 >>> 使用此方法改第三方UI库尤其方便!!!

值得一说的是 层级选择的第一个 必须是自己写死的

.radioTree /deep/ .ivu-checkbox-inner {

border-radius: 50%;

}

以上 完成iview radio-tree开发工作

成品图如下:

还有个关于tree的属性

是否可多选  multiple

不加的话只能选一个

:multiple='true'

加上之后可以选多个


this is all  !!!

2019.08.27 Mr.J

Logo

快速构建 Web 应用程序

更多推荐