先看效果图
image.png
<template>
<a-tree
v-model="checkedKeys"
checkable
:expanded-keys="expandedKeys"
:auto-expand-parent="autoExpandParent"
:selected-keys="selectedKeys"
:tree-data="treeData"
@expand="onExpand"
@select="onSelect"
@check="onCheck"
/>
</template>
<script>
const treeData = [
{
title: '0-0',
key: '0-0',
children: [
{
title: '0-0-0',
key: '0-0-0',
children: [
{title: '0-0-0-0', key: '0-0-0-0'},
{title: '0-0-0-1', key: '0-0-0-1'},
{title: '0-0-0-2', key: '0-0-0-2'},
],
},
{
title: '0-0-1',
key: '0-0-1',
children: [
{title: '0-0-1-0', key: '0-0-1-0'},
{title: '0-0-1-1', key: '0-0-1-1'},
{title: '0-0-1-2', key: '0-0-1-2'},
],
},
{
title: '0-0-2',
key: '0-0-2',
},
],
},
{
title: '0-1',
key: '0-1',
children: [
{title: '0-1-0-0', key: '0-1-0-0'},
{title: '0-1-0-1', key: '0-1-0-1'},
{title: '0-1-0-2', key: '0-1-0-2'},
],
},
{
title: '0-2',
key: '0-2',
},
];
export default {
data() {
return {
// 默认展开
expandedKeys: [],
// 是否自动展开父节点
autoExpandParent: true,
// 当前复选框被选中的节点 父亲与儿子也在同一个数组 所有儿子被选中则父亲也被选中
checkedKeys: [],
// 当前被点击的节点
selectedKeys: [],
// 树的信息,只包括 所有父亲与孩子的title和key
treeData,
};
},
watch: {
checkedKeys(val) {
// console.log('onCheck', val);
},
},
mounted() {
this.getTreeData()
},
methods: {
onExpand(expandedKeys) {
console.log('onExpand', expandedKeys);
// if not set autoExpandParent to false, if children expanded, parent can not collapse.
// or, you can remove all expanded children keys.
this.expandedKeys = expandedKeys;
this.autoExpandParent = false;
},
// 点击复选框触发
onCheck(checkedKeys) {
console.log('onCheck', checkedKeys);
this.checkedKeys = checkedKeys;
},
// 点击树节点触发
onSelect(selectedKeys, info) {
console.log(selectedKeys)
// console.log('onSelect', info);
this.selectedKeys = selectedKeys;
},
getTreeData() {
let treeArr = []
let page = require.context('@views', true, /.vue$/).keys();
page.forEach(item => {
// let item2 = item.substring(0, item.length - 4)
let item2 = item
// console.log(item2)
let arr = item2.split('/')
// console.log(arr)
arr.forEach((ele, index) => {
let path = ''
let parentId = ''
for (let i = 0; i <= index; i++) {
if (i == 0) {
path = '.'
parentId = ''
} else {
path = path + '/' + arr[i]
parentId = path.substring(0, path.length - arr[index].length - 1)
}
}
let obj = {
name: ele,
path: path,
id: path,
parentId: parentId
}
treeArr.push(obj)
})
})
console.log(treeArr)
// 去重
treeArr = this.unique(treeArr)
this.treeData = this.dgTree(treeArr, '.')
},
// 组装树
dgTree(arr, num) {
// console.log(arr)
let needArr = []
arr.forEach(item => {
if (item.parentId === num) {
needArr.push({
title: item.name,
key: item.id,
path: item.id,
children: this.dgTree(arr, item.id)
})
}
})
return needArr
},
unique(arr) {
const res = new Map();
return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
},
},
};
</script>
网友评论