包含全选以及树状图一维数组以及树形结构之前相互转换;
<!-- dom结构如下 -->
<el-checkbox
:indeterminate="isIndeterminate"
v-model="checkAll"
@change="handleCheckAllChange"
>全选</el-checkbox>
<el-tree
@check-change="handleCheckedChange"
:data="areaOptions"
show-checkbox
default-expand-all
ref="area"
node-key="id"
empty-text="加载中,请稍后"
:props="defaultProps"
></el-tree>
export default {
data() {
return {
/**定义变量**/
//半选
isIndeterminate: false,
//全选
checkAll: false,
//多维转一维数组
allAreaArr: [],
//模拟树状数据结构
areaOptions: [
{
id: 1,
label: '一级 1',
children: [
{
id: 4,
label: '二级 1-1',
children: [
{
id: 9,
label: '三级 1-1-1'
}, {
id: 10,
label: '三级 1-1-2'
}
]
}
]
},
],
//模拟一维数组
treeData: [
{"id":2,"name":"第一级1","pid":0},
{"id":3,"name":"第二级1","pid":2},
{"id":5,"name":"第三级1","pid":4},
{"id":100,"name":"第三级2","pid":3},
{"id":6,"name":"第三级2","pid":3},
{"id":601,"name":"第三级2","pid":6},
{"id":602,"name":"第三级2","pid":6},
{"id":603,"name":"第三级2","pid":6}
]
},
methods: {
/** 树形结构数据转单层数组形式*/
jsonToArray(nodes) {
let r = [];
if (Array.isArray(nodes)) {
for (let i = 0, l = nodes.length; i < l; i++) {
r.push(nodes[i]); // 取每项数据放入一个新数组
if (Array.isArray(nodes[i]["children"]) && nodes[i]["children"].length > 0)
// 若存在children则递归调用,把数据拼接到新数组中,并且删除该children
r = r.concat(this.jsonToArray(nodes[i]["children"]));
// delete nodes[i]["children"] //此项会更改原数组
}
}
return r;
},
/** 监听树状图change事件 判断全选或半选 */
handleCheckedChange($val,$checked,$node) {
let a = this.$refs.area.getCheckedKeys().length,
b = this.