树形控件
何时使用
文件夹、组织架构、生物分类、国家地区等等,世间万物的大多数结构都是树形结构。使用树控件
可以完整展现其中的层级关系,并具有展开收起选择等交互功能。
代码演示
- 0-0
- 0-0-0
- 0-0-0-0
- 0-0-0-1
- 0-0-0-2
- 0-0-1
- 0-0-1-0
- 0-0-1-1
- 0-0-1-2
- 0-0-2
- 0-0-0
- 0-1
- 0-2
受控操作示例
受控操作示例
<template>
<a-tree
v-model="checkedKeys"
checkable
:expanded-keys="expandedKeys"
:auto-expand-parent="autoExpandParent"
:selected-keys="selectedKeys"
:tree-data="treeData"
@expand="onExpand"
@select="onSelect"
/>
</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: ['0-0-0', '0-0-1'],
autoExpandParent: true,
checkedKeys: ['0-0-0'],
selectedKeys: [],
treeData,
};
},
watch: {
checkedKeys(val) {
console.log('onCheck', val);
},
},
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('onSelect', info);
this.selectedKeys = selectedKeys;
},
},
};
</script>
- parent 1
- 张晨成
- leaf
- leaf
- parent 1-1
- zcvc
- 张晨成
自定义TreeNode字段
替换treeNode中 title,key,children字段为treeData中对应的字段
<template>
<a-tree
checkable
:tree-data="treeData"
:default-expanded-keys="['0-0-0', '0-0-1']"
:default-selected-keys="['0-0-0', '0-0-1']"
:default-checked-keys="['0-0-0', '0-0-1']"
:replace-fields="replaceFields"
@select="onSelect"
@check="onCheck"
/>
</template>
<script>
const treeData = [
{
name: 'parent 1',
key: '0-0',
child: [
{
name: '张晨成',
key: '0-0-0',
disabled: true,
child: [
{ name: 'leaf', key: '0-0-0-0', disableCheckbox: true },
{ name: 'leaf', key: '0-0-0-1' },
],
},
{
name: 'parent 1-1',
key: '0-0-1',
child: [{ key: '0-0-1-0', name: 'zcvc' }],
},
],
},
];
export default {
data() {
return {
treeData,
replaceFields: {
children: 'child',
title: 'name',
},
};
},
methods: {
onSelect(selectedKeys, info) {
console.log('selected', selectedKeys, info);
},
onCheck(checkedKeys, info) {
console.log('onCheck', checkedKeys, info);
},
},
};
</script>
- 0-0
- 0-0-0
- 0-0-0-0
- 0-0-0-1
- 0-0-0-2
- 0-0-1
- 0-0-2
- 0-0-0
- 0-1
- 0-2
拖动示例
将节点拖拽到其他节点内部或前后。
<template>
<a-tree
class="draggable-tree"
:default-expanded-keys="expandedKeys"
draggable
:tree-data="gData"
@dragenter="onDragEnter"
@drop="onDrop"
/>
</template>
<script>
const x = 3;
const y = 2;
const z = 1;
const gData = [];
const generateData = (_level, _preKey, _tns) => {
const preKey = _preKey || '0';
const tns = _tns || gData;
const children = [];
for (let i = 0; i < x; i++) {
const key = `${preKey}-${i}`;
tns.push({ title: key, key });
if (i < y) {
children.push(key);
}
}
if (_level < 0) {
return tns;
}
const level = _level - 1;
children.forEach((key, index) => {
tns[index].children = [];
return generateData(level, key, tns[index].children);
});
};
generateData(z);
export default {
data() {
return {
gData,
expandedKeys: ['0-0', '0-0-0', '0-0-0-0'],
};
},
methods: {
onDragEnter(info) {
console.log(info);
// expandedKeys 需要受控时设置
// this.expandedKeys = info.expandedKeys
},
onDrop(info) {
console.log(info);
const dropKey = info.node.eventKey;
const dragKey = info.dragNode.eventKey;
const dropPos = info.node.pos.split('-');
const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
const loop = (data, key, callback) => {
data.forEach((item, index, arr) => {
if (item.key === key) {
return callback(item, index, arr);
}
if (item.children) {
return loop(item.children, key, callback);
}
});
};
const data = [...this.gData];
// Find dragObject
let dragObj;
loop(data, dragKey, (item, index, arr) => {
arr.splice(index, 1);
dragObj = item;
});
if (!info.dropToGap) {
// Drop on the content
loop(data, dropKey, item => {
item.children = item.children || [];
// where to insert 示例添加到尾部,可以是随意位置
item.children.push(dragObj);
});
} else if (
(info.node.children || []).length > 0 && // Has children
info.node.expanded && // Is expanded
dropPosition === 1 // On the bottom gap
) {
loop(data, dropKey, item => {
item.children = item.children || [];
// where to insert 示例添加到尾部,可以是随意位置
item.children.unshift(dragObj);
});
} else {
let ar;
let i;
loop(data, dropKey, (item, index, arr) => {
ar = arr;
i = index;
});
if (dropPosition === -1) {
ar.splice(i, 0, dragObj);
} else {
ar.splice(i + 1, 0, dragObj);
}
}
this.gData = data;
},
},
};
</script>
连接线
带连接线的树。
<template>
<div>
<div style="margin-bottom: 16px">
showLine: <a-switch v-model="showLine" />
<br />
<br />
showIcon: <a-switch v-model="showIcon" />
</div>
<a-tree
:show-line="showLine"
:show-icon="showIcon"
:default-expanded-keys="['0-0-0', '0-0-1', '0-0-2']"
@select="onSelect"
>
<a-icon slot="icon" type="carry-out" />
<a-tree-node key="0-0">
<a-icon slot="icon" type="carry-out" />
<span slot="title" style="color: #1890ff">parent 1</span>
<a-tree-node key="0-0-0" title="parent 1-0">
<a-icon slot="icon" type="carry-out" />
<a-tree-node key="0-0-0-0" title="leaf">
<a-icon slot="icon" type="carry-out" />
</a-tree-node>
<a-tree-node key="0-0-0-1" title="leaf">
<a-icon slot="icon" type="carry-out" />
</a-tree-node>
<a-tree-node key="0-0-0-2" title="leaf">
<a-icon slot="icon" type="carry-out" />
</a-tree-node>
</a-tree-node>
<a-tree-node key="0-0-1" title="parent 1-1">
<a-icon slot="icon" type="carry-out" />
<a-tree-node key="0-0-1-0" title="leaf">
<a-icon slot="icon" type="carry-out" />
</a-tree-node>
</a-tree-node>
<a-tree-node key="0-0-2" title="parent 1-2">
<a-icon slot="icon" type="carry-out" />
<a-tree-node key="0-0-2-0" title="leaf">
<a-icon slot="icon" type="carry-out" />
</a-tree-node>
<a-tree-node key="0-0-2-1" title="leaf">
<a-icon slot="icon" type="carry-out" />
<a-icon slot="switcherIcon" type="form" />
</a-tree-node>
</a-tree-node>
</a-tree-node>
</a-tree>
</div>
</template>
<script>
export default {
data() {
return {
showLine: true,
showIcon: false,
};
},
methods: {
onSelect(selectedKeys, info) {
console.log('selected', selectedKeys, info);
},
},
};
</script>
- **parent 0
- leaf 0-0
- leaf 0-1
- **parent 1
- leaf 1-0
- leaf 1-1
目录
内置的目录树,multiple
模式支持 ctrl(Windows)
/ command(Mac)
复选。
<template>
<a-directory-tree multiple default-expand-all @select="onSelect" @expand="onExpand">
<a-tree-node key="0-0" title="parent 0">
<a-tree-node key="0-0-0" title="leaf 0-0" is-leaf />
<a-tree-node key="0-0-1" title="leaf 0-1" is-leaf />
</a-tree-node>
<a-tree-node key="0-1" title="parent 1">
<a-tree-node key="0-1-0" title="leaf 1-0" is-leaf />
<a-tree-node key="0-1-1" title="leaf 1-1" is-leaf />
</a-tree-node>
</a-directory-tree>
</template>
<script>
export default {
methods: {
onSelect(keys, event) {
console.log('Trigger Select', keys, event);
},
onExpand() {
console.log('Trigger Expand');
},
},
};
</script>
- parent 1
- parent 1-0
- leaf
- leaf
- parent 1-1
- sss
- parent 1-0
基本用法
最简单的用法,展示可勾选,可选中,禁用,默认展开等功能。
<template>
<a-tree
checkable
:tree-data="treeData"
:default-expanded-keys="['0-0-0', '0-0-1']"
:default-selected-keys="['0-0-0', '0-0-1']"
:default-checked-keys="['0-0-0', '0-0-1']"
@select="onSelect"
@check="onCheck"
>
<span slot="title0010" style="color: #1890ff">sss</span>
</a-tree>
</template>
<script>
const treeData = [
{
title: 'parent 1',
key: '0-0',
children: [
{
title: 'parent 1-0',
key: '0-0-0',
disabled: true,
children: [
{ title: 'leaf', key: '0-0-0-0', disableCheckbox: true },
{ title: 'leaf', key: '0-0-0-1' },
],
},
{
title: 'parent 1-1',
key: '0-0-1',
children: [{ key: '0-0-1-0', slots: { title: 'title0010' } }],
},
],
},
];
export default {
data() {
return {
treeData,
};
},
methods: {
onSelect(selectedKeys, info) {
console.log('selected', selectedKeys, info);
},
onCheck(checkedKeys, info) {
console.log('onCheck', checkedKeys, info);
},
},
};
</script>
- **parent 1
- leaf
- leaf
自定义图标
可以针对不同的节点定制图标。
<template>
<a-tree :tree-data="treeData" show-icon default-expand-all :default-selected-keys="['0-0-0']">
<a-icon slot="switcherIcon" type="down" />
<a-icon slot="smile" type="smile-o" />
<a-icon slot="meh" type="smile-o" />
<template slot="custom" slot-scope="{ selected }">
<a-icon :type="selected ? 'frown' : 'frown-o'" />
</template>
</a-tree>
</template>
<script>
const treeData = [
{
title: 'parent 1',
key: '0-0',
slots: {
icon: 'smile',
},
children: [
{ title: 'leaf', key: '0-0-0', slots: { icon: 'meh' } },
{ title: 'leaf', key: '0-0-1', scopedSlots: { icon: 'custom' } },
],
},
];
export default {
data() {
return {
treeData,
};
},
methods: {
onSelect(selectedKeys, info) {
console.log('selected', selectedKeys, info);
},
onCheck(checkedKeys, info) {
console.log('onCheck', checkedKeys, info);
},
},
};
</script>
- Expand to load
- Expand to load
- Tree Node
异步数据加载
点击展开节点,动态加载数据。
<template>
<a-tree :load-data="onLoadData" :tree-data="treeData" />
</template>
<script>
export default {
data() {
return {
treeData: [
{ title: 'Expand to load', key: '0' },
{ title: 'Expand to load', key: '1' },
{ title: 'Tree Node', key: '2', isLeaf: true },
],
};
},
methods: {
onLoadData(treeNode) {
return new Promise(resolve => {
if (treeNode.dataRef.children) {
resolve();
return;
}
setTimeout(() => {
treeNode.dataRef.children = [
{ title: 'Child Node', key: `${treeNode.eventKey}-0` },
{ title: 'Child Node', key: `${treeNode.eventKey}-1` },
];
this.treeData = [...this.treeData];
resolve();
}, 1000);
});
},
},
};
</script>
可搜索
可搜索的树。
<template>
<div>
<a-input-search style="margin-bottom: 8px" placeholder="Search" @change="onChange" />
<a-tree
:expanded-keys="expandedKeys"
:auto-expand-parent="autoExpandParent"
:tree-data="gData"
@expand="onExpand"
>
<template slot="title" slot-scope="{ title }">
<span v-if="title.indexOf(searchValue) > -1">
{{ title.substr(0, title.indexOf(searchValue)) }}
<span style="color: #f50">{{ searchValue }}</span>
{{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
</span>
<span v-else>{{ title }}</span>
</template>
</a-tree>
</div>
</template>
<script>
const x = 3;
const y = 2;
const z = 1;
const gData = [];
const generateData = (_level, _preKey, _tns) => {
const preKey = _preKey || '0';
const tns = _tns || gData;
const children = [];
for (let i = 0; i < x; i++) {
const key = `${preKey}-${i}`;
tns.push({ title: key, key, scopedSlots: { title: 'title' } });
if (i < y) {
children.push(key);
}
}
if (_level < 0) {
return tns;
}
const level = _level - 1;
children.forEach((key, index) => {
tns[index].children = [];
return generateData(level, key, tns[index].children);
});
};
generateData(z);
const dataList = [];
const generateList = data => {
for (let i = 0; i < data.length; i++) {
const node = data[i];
const key = node.key;
dataList.push({ key, title: key });
if (node.children) {
generateList(node.children);
}
}
};
generateList(gData);
const getParentKey = (key, tree) => {
let parentKey;
for (let i = 0; i < tree.length; i++) {
const node = tree[i];
if (node.children) {
if (node.children.some(item => item.key === key)) {
parentKey = node.key;
} else if (getParentKey(key, node.children)) {
parentKey = getParentKey(key, node.children);
}
}
}
return parentKey;
};
export default {
data() {
return {
expandedKeys: [],
searchValue: '',
autoExpandParent: true,
gData,
};
},
methods: {
onExpand(expandedKeys) {
this.expandedKeys = expandedKeys;
this.autoExpandParent = false;
},
onChange(e) {
const value = e.target.value;
const expandedKeys = dataList
.map(item => {
if (item.title.indexOf(value) > -1) {
return getParentKey(item.key, gData);
}
return null;
})
.filter((item, i, self) => item && self.indexOf(item) === i);
Object.assign(this, {
expandedKeys,
searchValue: value,
autoExpandParent: true,
});
},
},
};
</script>
- parent 1
- parent 1-0
- leaf
- leaf
- leaf
- parent 1-1
- parent 1-2
- parent 1-0
自定义展开/折叠图标
自定义展开/折叠图标。
<template>
<a-tree show-line :default-expanded-keys="['0-0-0']" @select="onSelect">
<a-icon slot="switcherIcon" type="down" />
<a-tree-node key="0-0" title="parent 1">
<a-tree-node key="0-0-0" title="parent 1-0">
<a-tree-node key="0-0-0-0" title="leaf" />
<a-tree-node key="0-0-0-1" title="leaf" />
<a-tree-node key="0-0-0-2" title="leaf" />
</a-tree-node>
<a-tree-node key="0-0-1" title="parent 1-1">
<a-tree-node key="0-0-1-0" title="leaf" />
</a-tree-node>
<a-tree-node key="0-0-2" title="parent 1-2">
<a-tree-node key="0-0-2-0" title="leaf" />
<a-tree-node key="0-0-2-1" title="leaf" />
</a-tree-node>
</a-tree-node>
</a-tree>
</template>
<script>
export default {
methods: {
onSelect(selectedKeys, info) {
console.log('selected', selectedKeys, info);
},
},
};
</script>
API
Tree props
参数 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
blockNode | 是否节点占据一行 | boolean | false | 1.5.0 |
treeData | treeNodes 数据,如果设置则不需要手动构造 TreeNode 节点(key 在整个树范围内唯一) | array<{key, title, children, [disabled, selectable]}> | — | |
replaceFields | 替换 treeNode 中 title,key,children 字段为 treeData 中对应的字段 | object | {children:’children’, title:’title’, key:’key’ } | |
autoExpandParent | 是否自动展开父节点 | boolean | true | |
checkable | 节点前添加 Checkbox 复选框 | boolean | false | |
checkedKeys(v-model) | (受控)选中复选框的树节点(注意:父子节点有关联,如果传入父节点 key,则子节点自动选中;相应当子节点 key 都传入,父节点也自动选中。当设置checkable 和checkStrictly ,它是一个有checked 和halfChecked 属性的对象,并且父子节点的选中与否不再关联 | string[] | number[] | {checked: string[] | number[], halfChecked: string[] | number[]} | [] | |
checkStrictly | checkable 状态下节点选择完全受控(父子节点选中状态不再关联) | boolean | false | |
defaultCheckedKeys | 默认选中复选框的树节点 | string[] | number[] | [] | |
defaultExpandAll | 默认展开所有树节点 | boolean | false | |
defaultExpandedKeys | 默认展开指定的树节点 | string[] | number[] | [] | |
defaultExpandParent | 默认展开父节点 | bool | true | |
defaultSelectedKeys | 默认选中的树节点 | string[] | number[] | [] | |
disabled | 将树禁用 | bool | false | |
draggable | 设置节点可拖拽 | boolean | false | |
expandedKeys(.sync) | (受控)展开指定的树节点 | string[] | number[] | [] | |
filterTreeNode | 按需筛选树节点(高亮),返回 true | function(node) | - | |
loadData | 异步加载数据 | function(node) | - | |
loadedKeys | (受控)已经加载的节点,需要配合 loadData 使用 | string[] | number[] | [] | |
multiple | 支持点选多个节点(节点本身) | boolean | false | |
selectable | 是否可选中 | boolean | true | |
selectedKeys(.sync) | (受控)设置选中的树节点 | string[] | number[] | - | |
showIcon | 是否展示 TreeNode title 前的图标,没有默认样式,如设置为 true,需要自行定义图标相关样式 | boolean | false | |
switcherIcon | 自定义树节点的展开/折叠图标 | slot | - | |
showLine | 是否展示连接线 | boolean | false |
事件
事件名称 | 说明 | 回调参数 |
---|---|---|
check | 点击复选框触发 | function(checkedKeys, e:{checked: bool, checkedNodes, node, event}) |
dragend | dragend 触发时调用 | function({event, node}) |
dragenter | dragenter 触发时调用 | function({event, node, expandedKeys}) |
dragleave | dragleave 触发时调用 | function({event, node}) |
dragover | dragover 触发时调用 | function({event, node}) |
dragstart | 开始拖拽时调用 | function({event, node}) |
drop | drop 触发时调用 | function({event, node, dragNode, dragNodesKeys}) |
expand | 展开/收起节点时触发 | function(expandedKeys, {expanded: bool, node}) |
load | 节点加载完毕时触发 | function(loadedKeys, {event, node}) |
rightClick | 响应右键点击 | function({event, node}) |
select | 点击树节点触发 | function(selectedKeys, e:{selected: bool, selectedNodes, node, event}) |
TreeNode props
结点描述数据对象,是 treeNodes 中的一项,TreeNode 使用相同的 API。
参数 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
class | 节点的 class | string | - | |
style | 节点的 style | string|object | - | |
checkable | 当树为 checkable 时,设置独立节点是否展示 Checkbox | boolean | - | 1.5.0 |
disableCheckbox | 禁掉 checkbox | boolean | false | |
disabled | 禁掉响应 | boolean | false | |
icon | 自定义图标。可接收组件,props 为当前节点 props | slot|slot-scope | - | |
isLeaf | 设置为叶子节点(设置了loadData 时有效) | boolean | false | |
key | 被树的 (default)ExpandedKeys / (default)CheckedKeys / (default)SelectedKeys 属性所用。注意:整个树范围内的所有节点的 key 值不能重复! | string | number | 内部计算出的节点位置 | |
selectable | 设置节点是否可被选中 | boolean | true | |
title | 标题 | string|slot|slot-scope | ‘—-‘ | |
slots | 使用 treeNodes 时,可以通过该属性配置支持 slot 的属性,如 slots: { title: ‘XXX’} | object | - | |
scopedSlots | 使用 columns 时,可以通过该属性配置支持 slot-scope 的属性,如 scopedSlots: { title: ‘XXX’} | object | - | |
on | 事件对象,仅在 treeNodes 使用方式中生效,如{click: () => {}} | object | ‘—-‘ |
DirectoryTree props
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
expandAction | 目录展开逻辑,可选 false ‘click’ ‘dblclick’ | string | click |
FAQ
在 showLine 时,如何隐藏子节点图标?
文件图标通过 switcherIcon 来实现,如果不需要你可以覆盖对应的样式