全选/不全选
方法1
<template>部分
<div>
<!-- 复选框,点击事件 -->
<el-checkbox v-model="isSelectAll" @change="selectAll">全选/全不选</el-checkbox>
<!-- 要操作的树组件,必须要有 ref,node-key-->
<el-tree ref="myTree"
v-bind="myTree"
node-key="id"
show-checkbox
:default-expand-all="isExpand"
:filter-node-method="filterNode"
/>
</div>
<script>部分
export default {
data(){
return {
myTree: {
data: [],
props: { children: 'children', label: 'name' }
},
isSelectAll: false
}
},
methods: {
getTreeData() {
this.myTree.data = xxx得到树的数据
xxx其他操作
},
selectAll() {
if (this.isSelectAll) {
this.$refs.organizationData.setCheckedNodes(this.myTree.data);
} else {
this.$refs.menuOrUserTree.setCheckedNodes([])
}
}
}
}
优:简单,好实现
缺:扩展性差,不够灵活
方法2
获取el-tree 子节点,
<template>部分
<div>
<!-- 复选框,点击事件 -->
<el-checkbox v-model="isSelectAll" @change="selectAll">全选/全不选</el-checkbox>
<!-- 要操作的树组件,必须要有 ref,node-key-->
<el-tree ref="myTree"
v-bind="myTree"
node-key="id"
show-checkbox
:default-expand-all="isExpand"
:filter-node-method="filterNode"
/>
</div>
<script>
export default {
data(){
return {
myTree: {
data: [],
props: { children: 'children', label: 'name' }
},
treeAllChildNode: [],
isSelectAll: false
}
},
methods: {
getTreeData() {
this.myTree.data = xxx得到树的数据
this.treeAllChildNode = []
this.getTreeAllChildNode(this.myTree.data)
xxx其他操作
},
getTreeAllChildNode(treeData) {
if (treeData.length === 0) {
return
}
for (let i = 0; i < treeData.length; i++) {
let children = treeData[i].children
if (children && children.length > 0) {
this.getTreeAllChildNode(children)
} else if (treeData[i].disabled === false) {
this.treeAllChildNode.push(treeData[i].id)
}
}
},
selectAll() {
if (this.isSelectAll) {
for (let i = 0; i < this.treeAllChildNode.length; i++) {
this.$refs['menuOrUserTree'].setChecked(this.treeAllChildNode[i], true, false)
}
} else {
this.$refs.menuOrUserTree.setCheckedNodes([])
}
},
}
}
优:扩展性强(可自定义选中的数据,并且对不可选中的选项做筛选),可自定义选择
缺:写的多
注意事项:
每次获取树数据需要对字节点数组(对象)进行清空
树(el-tree)一键展开和折叠
具体看代码
<template>部分
<div>
<!-- 复选框,且带有点击事件 -->
<el-checkbox v-model="isExpand" @change="expandAll">展开/折叠</el-checkbox>
<!-- 操作的树组件 -->
<el-tree ref="myTree"
v-bind="myTree"
node-key="id"
show-checkbox
:default-expand-all="isExpand"
:filter-node-method="filterNode"
/>
</div>
<script>部分
export default {
data(){
return {
isExpand: true
}
},
methods: {
expandAll() {
for (var i = 0; i < this.$refs.myTree.store._getAllNodes().length; i++) {
this.$refs.myTree.store._getAllNodes()[i].expanded = this.isExpand
}
}
}
}
|