记录使用elementui的el-tree实现全选多选单选遇到的一些问题
这是最近在做项目时遇到的问题,今天特意做一些笔记,记录一下遇到的问题,项目要求实现全选多选单选,并根据选择的id做一个精确查询。因为我们用的框架是elementUI,所以自然而然的想到用el-tree
来实现基本的HTML,如下:
<div class="checked-all"> <fin-checkbox v-model="checkAll" :indeterminate="pickStatus == 1" @change="checkedAll" >全选</fin-checkbox > </div> <fin-tree ref="appTree" :data="appLists" show-checkbox node-key="id" :props="defaultProps" default-expand-all @check="checkedSingle" ></fin-tree>
el-tree的一些配置这里就不说了,大家上官网一看就知道,我主要说说实现方式和遇到的一些问题。
首先看看全选:
遍历所有的节点,并设置其checkAll属性为true或false
// 全选或反选 checkedAll() { this.pickStatus = 0; if (this.checkAll) { // 全选 this.$refs.appTree.setCheckedNodes(this.appLists); this.$nextTick(() => { const getAllIds = this.$refs.appTree.getCheckedNodes(this.appLists); const showIds = getAllIds.map((item) => item.id); //获取选择id // 调用后台接口查询 getcompLists({ arrAppIds: showIds.join(',') }).then((res) => { this.components = res; }); }); } else { // 取消选中 this.$refs.appTree.setCheckedKeys([]); } },
关键就是通过设置node或key:
//全选 this.$refs.tree.setCheckedNodes(this.treeData); // this.$refs.tree.setCheckedKeys([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); //清空 // this.$refs.tree.setCheckedNodes([]); this.$refs.tree.setCheckedKeys([]);
单选多选实现:
// 单选及多选 checkedSingle() { const keys = [ //得到id值,合并全选半选值 ...this.$refs.appTree.getCheckedKeys(), ...this.$refs.appTree.getHalfCheckedKeys(), ]; if (keys.length == false) { this.getcompLists(); // 如果没有任何选择重新渲染 } else { const iDStr = keys.join(','); getcompLists({ arrAppIds: iDStr }).then((res) => { this.components = res; }); } },
这里的getCheckedKeys 则返回目前半选中的节点的 node-key 的值 所组成的数组,getHalfCheckedKeys是获取半选状态下的值,然后通过… 展开运算符 把得到的数组展开并合并,这是最关键的点。
还有就是需要注意的是使用el-tree来实现全选的时候el-tree内的单个节点点击方法要使用check即当复选框被点击的时候触发,不要使用check-change方法,否则,会重复获取节点,后台报错。
声明:
1. 本站所有文章教程及资源素材均来源于网络与用户分享或为本站原创,仅限用于学习和研究。
2. 如果内容损害你的权益请联系客服QQ:1642748312给予处理。
码云笔记 » 记录使用elementui的el-tree实现全选多选单选遇到的一些问题
1. 本站所有文章教程及资源素材均来源于网络与用户分享或为本站原创,仅限用于学习和研究。
2. 如果内容损害你的权益请联系客服QQ:1642748312给予处理。
码云笔记 » 记录使用elementui的el-tree实现全选多选单选遇到的一些问题