Tree 树形控件
多层次的结构列表。
何时使用
文件夹、组织架构、生物分类、国家地区等等,世间万物的大多数结构都是树形结构。使用树控件
可以完整展现其中的层级关系,并具有展开收起选择等交互功能。
代码演示
- parent 1
- parent 1-0
- leaf
- leaf
- parent 1-1
- sss
- parent 1-0
最简单的用法,展示可勾选,可选中,禁用,默认展开等功能。
<template>
<a-tree
checkable
:tree-data="treeData"
v-model:expandedKeys="expandedKeys"
v-model:selectedKeys="selectedKeys"
v-model:checkedKeys="checkedKeys"
>
<template #title0010><span style="color: #1890ff">sss</span></template>
</a-tree>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
const treeData: TreeDataItem[] = [
{
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 defineComponent({
setup() {
const expandedKeys = ref<string[]>(['0-0-0', '0-0-1']);
const selectedKeys = ref<string[]>(['0-0-0', '0-0-1']);
const checkedKeys = ref<string[]>(['0-0-0', '0-0-1']);
watch(expandedKeys, () => {
console.log('expandedKeys', expandedKeys);
});
watch(selectedKeys, () => {
console.log('selectedKeys', selectedKeys);
});
watch(checkedKeys, () => {
console.log('checkedKeys', checkedKeys);
});
return {
treeData,
expandedKeys,
selectedKeys,
checkedKeys,
};
},
});
</script>
- Expand to load
- Expand to load
- Tree Node
点击展开节点,动态加载数据。
<template>
<a-tree
:load-data="onLoadData"
:tree-data="treeData"
v-model:expandedKeys="expandedKeys"
v-model:selectedKeys="selectedKeys"
/>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
export default defineComponent({
setup() {
const expandedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);
const treeData = ref<TreeDataItem[]>([
{ title: 'Expand to load', key: '0' },
{ title: 'Expand to load', key: '1' },
{ title: 'Tree Node', key: '2', isLeaf: true },
]);
const onLoadData = (treeNode: any) => {
return new Promise((resolve: (value?: unknown) => void) => {
if (treeNode.dataRef.children) {
resolve();
return;
}
setTimeout(() => {
treeNode.dataRef.children = [
{ title: 'Child Node', key: `${treeNode.eventKey}-0` },
{ title: 'Child Node', key: `${treeNode.eventKey}-1` },
];
treeData.value = [...treeData.value];
resolve();
}, 1000);
});
};
return {
expandedKeys,
selectedKeys,
treeData,
onLoadData,
};
},
});
</script>
可搜索的树。
<template>
<div>
<a-input-search v-model:value="searchValue" style="margin-bottom: 8px" placeholder="Search" />
<a-tree
v-model:expandedKeys="expandedKeys"
:auto-expand-parent="autoExpandParent"
:tree-data="gData"
>
<template #title="{ 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 lang="ts">
import { defineComponent, ref, watch } from 'vue';
import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
const x = 3;
const y = 2;
const z = 1;
const genData: TreeDataItem[] = [];
const generateData = (_level: number, _preKey?: string, _tns?: TreeDataItem[]) => {
const preKey = _preKey || '0';
const tns = _tns || genData;
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);
const dataList: TreeDataItem[] = [];
const generateList = (data: TreeDataItem[]) => {
for (let i = 0; i < data.length; i++) {
const node = data[i];
const key = node.key;
dataList.push({ key, title: key as string });
if (node.children) {
generateList(node.children);
}
}
};
generateList(genData);
const getParentKey = (key: string, tree: TreeDataItem[]): string | number | undefined => {
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 defineComponent({
setup() {
const expandedKeys = ref<string[]>([]);
const searchValue = ref<string>('');
const autoExpandParent = ref<boolean>(true);
const gData = ref<TreeDataItem[]>(genData);
watch(expandedKeys, () => {
autoExpandParent.value = false;
});
watch(searchValue, value => {
const expanded = dataList
.map((item: TreeDataItem) => {
if (item.title.indexOf(value) > -1) {
return getParentKey(item.key, gData.value);
}
return null;
})
.filter((item, i, self) => item && self.indexOf(item) === i);
expandedKeys.value = expanded as string[];
searchValue.value = value;
autoExpandParent.value = true;
});
return {
expandedKeys,
searchValue,
autoExpandParent,
gData,
};
},
});
</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
v-model:expandedKeys="expandedKeys"
v-model:selectedKeys="selectedKeys"
>
<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 lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const expandedKeys = ref<string[]>(['0-0', '0-1']);
const selectedKeys = ref<string[]>([]);
return {
expandedKeys,
selectedKeys,
};
},
});
</script>
- parent 1
- 张晨成
- leaf
- leaf
- parent 1-1
- zcvc
- 张晨成
替换treeNode中 title,key,children字段为treeData中对应的字段
<template>
<a-tree
checkable
:tree-data="treeData"
v-model:expandedKeys="expandedKeys"
v-model:selectedKeys="selectedKeys"
v-model:checkedKeys="checkedKeys"
:replace-fields="replaceFields"
/>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
export default defineComponent({
setup() {
const expandedKeys = ref<string[]>(['0-0-0', '0-0-1']);
const selectedKeys = ref<string[]>(['0-0-0', '0-0-1']);
const checkedKeys = ref<string[]>(['0-0-0', '0-0-1']);
const replaceFields = {
children: 'child',
title: 'name',
};
const treeData: TreeDataItem[] = [
{
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' }],
},
],
},
];
watch(expandedKeys, () => {
console.log('expandedKeys', expandedKeys);
});
watch(selectedKeys, () => {
console.log('selectedKeys', selectedKeys);
});
watch(checkedKeys, () => {
console.log('checkedKeys', checkedKeys);
});
return {
expandedKeys,
selectedKeys,
checkedKeys,
replaceFields,
treeData: ref(treeData),
};
},
});
</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"
v-model:expandedKeys="expandedKeys"
draggable
:tree-data="gData"
@dragenter="onDragEnter"
@drop="onDrop"
/>
</template>
<script lang="ts">
import { defineComponent, ref, VNode } from 'vue';
import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
interface DragEnterEvent {
event: DragEvent;
expandedKeys: string[];
node: VNode;
}
interface DropEvent {
dragNode: any;
dragNodesKeys: string[];
dropPosition: number;
dropToGap: boolean;
event: DragEvent;
node: any;
}
const x = 3;
const y = 2;
const z = 1;
const genData: TreeDataItem[] = [];
const generateData = (_level: number, _preKey?: string, _tns?: TreeDataItem[]) => {
const preKey = _preKey || '0';
const tns = _tns || genData;
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 defineComponent({
setup() {
const expandedKeys = ref<string[]>(['0-0', '0-0-0', '0-0-0-0']);
const gData = ref<TreeDataItem[]>(genData);
const onDragEnter = (info: DragEnterEvent) => {
console.log(info);
// expandedKeys 需要展开时
// expandedKeys.value = info.expandedKeys
};
const onDrop = (info: DropEvent) => {
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: TreeDataItem[], key: string, callback: any) => {
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 = [...gData.value];
// Find dragObject
let dragObj: TreeDataItem = {};
loop(data, dragKey, (item: TreeDataItem, index: number, arr: TreeDataItem[]) => {
arr.splice(index, 1);
dragObj = item;
});
if (!info.dropToGap) {
// Drop on the content
loop(data, dropKey, (item: TreeDataItem) => {
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: TreeDataItem) => {
item.children = item.children || [];
// where to insert 示例添加到尾部,可以是随意位置
item.children.unshift(dragObj);
});
} else {
let ar: TreeDataItem[] = [];
let i = 0;
loop(data, dropKey, (item: TreeDataItem, index: number, arr: TreeDataItem[]) => {
ar = arr;
i = index;
});
if (dropPosition === -1) {
ar.splice(i, 0, dragObj);
} else {
ar.splice(i + 1, 0, dragObj);
}
}
gData.value = data;
};
return {
expandedKeys,
gData,
onDragEnter,
onDrop,
};
},
});
</script>
- parent 1
- leaf
- leaf
可以针对不同的节点定制图标。
<template>
<a-tree :tree-data="treeData" show-icon default-expand-all v-model:selectedKeys="selectedKeys">
<template #switcherIcon>
<down-outlined />
</template>
<template #smile>
<smile-outlined />
</template>
<template #meh>
<smile-outlined />
</template>
<template #custom="{ selected }">
<frown-filled v-if="selected" />
<frown-outlined v-else />
</template>
</a-tree>
</template>
<script lang="ts">
import { DownOutlined, SmileOutlined, FrownOutlined, FrownFilled } from '@ant-design/icons-vue';
import { defineComponent, ref } from 'vue';
import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
const treeData: TreeDataItem[] = [
{
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', slots: { icon: 'custom' } },
],
},
];
export default defineComponent({
components: {
DownOutlined,
SmileOutlined,
FrownOutlined,
FrownFilled,
},
setup() {
return {
selectedKeys: ref(['0-0-0']),
treeData,
};
},
});
</script>
节点之间带连接线的树,常用于文件目录结构展示。使用 showLine
开启,可以用 switcherIcon
修改默认图标。
<template>
<div>
<div style="margin-bottom: 16px">
showLine:
<a-switch v-model:checked="showLine" />
<br />
<br />
showIcon:
<a-switch v-model:checked="showIcon" />
</div>
<a-tree
:show-line="showLine"
:show-icon="showIcon"
:default-expanded-keys="['0-0-0', '0-0-1', '0-0-2']"
@select="onSelect"
>
<template #icon><carry-out-outlined /></template>
<a-tree-node key="0-0">
<template #icon><carry-out-outlined /></template>
<template #title><span style="color: #1890ff">parent 1</span></template>
<a-tree-node title="parent 1-0" key="0-0-0">
<template #icon><carry-out-outlined /></template>
<a-tree-node title="leaf" key="0-0-0-0">
<template #icon><carry-out-outlined /></template>
</a-tree-node>
<a-tree-node title="leaf" key="0-0-0-1">
<template #icon><carry-out-outlined /></template>
</a-tree-node>
<a-tree-node title="leaf" key="0-0-0-2">
<template #icon><carry-out-outlined /></template>
</a-tree-node>
</a-tree-node>
<a-tree-node title="parent 1-1" key="0-0-1">
<template #icon><carry-out-outlined /></template>
<a-tree-node title="leaf" key="0-0-1-0">
<template #icon><carry-out-outlined /></template>
</a-tree-node>
</a-tree-node>
<a-tree-node title="parent 1-2" key="0-0-2">
<template #icon><carry-out-outlined /></template>
<a-tree-node title="leaf" key="0-0-2-0">
<template #icon><carry-out-outlined /></template>
</a-tree-node>
<a-tree-node title="leaf" key="0-0-2-1">
<template #icon><carry-out-outlined /></template>
<template #switcherIcon><form-outlined /></template>
</a-tree-node>
</a-tree-node>
</a-tree-node>
</a-tree>
</div>
</template>
<script lang="ts">
import { CarryOutOutlined, FormOutlined } from '@ant-design/icons-vue';
import { SelectEvent } from 'ant-design-vue/es/tree/Tree';
import { defineComponent, ref } from 'vue';
export default defineComponent({
components: {
CarryOutOutlined,
FormOutlined,
},
setup() {
const showLine = ref<boolean>(true);
const showIcon = ref<boolean>(false);
const onSelect = (selectedKeys: string[], info: SelectEvent) => {
console.log('selected', selectedKeys, info);
};
return {
showLine,
showIcon,
onSelect,
};
},
});
</script>
- parent 1
- parent 1-0
- leaf
- leaf
- leaf
- parent 1-1
- parent 1-2
- parent 1-0
自定义展开/折叠图标。
<template>
<a-tree showLine v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys">
<template #switcherIcon><down-outlined /></template>
<a-tree-node title="parent 1" key="0-0">
<a-tree-node title="parent 1-0" key="0-0-0">
<a-tree-node title="leaf" key="0-0-0-0" />
<a-tree-node title="leaf" key="0-0-0-1" />
<a-tree-node title="leaf" key="0-0-0-2" />
</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 lang="ts">
import { DownOutlined } from '@ant-design/icons-vue';
import { defineComponent, ref } from 'vue';
export default defineComponent({
components: {
DownOutlined,
},
setup() {
const expandedKeys = ref<string[]>(['0-0-0']);
const selectedKeys = ref<string[]>([]);
return {
expandedKeys,
selectedKeys,
};
},
});
</script>
API
Tree props
参数 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
blockNode | 是否节点占据一行 | boolean | false | |
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 | |
defaultExpandAll | 默认展开所有树节点, 如果是异步数据,需要在数据返回后再实例化,建议用 v-if=”data.length”;当有 expandedKeys 时,defaultExpandAll 将失效 | boolean | false | |
disabled | 将树禁用 | bool | false | |
draggable | 设置节点可拖拽 | boolean | false | |
expandedKeys(v-model) | (受控)展开指定的树节点 | string[] | number[] | [] | |
filterTreeNode | 按需筛选树节点(高亮),返回 true | function(node) | - | |
loadData | 异步加载数据 | function(node) | - | |
loadedKeys | (受控)已经加载的节点,需要配合 loadData 使用 | string[] | number[] | [] | |
multiple | 支持点选多个节点(节点本身) | boolean | false | |
selectable | 是否可选中 | boolean | true | |
selectedKeys(v-model) | (受控)设置选中的树节点 | string[] | number[] | - | |
showIcon | 是否展示 TreeNode title 前的图标,没有默认样式,如设置为 true,需要自行定义图标相关样式 | boolean | false | |
switcherIcon | 自定义树节点的展开/折叠图标 | slot | - | |
showLine | 是否展示连接线 | boolean | false | |
title | 标题 | slot | 2.0.0 |
事件
事件名称 | 说明 | 回调参数 |
---|---|---|
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 | - | |
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 | - |
DirectoryTree props
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
expandAction | 目录展开逻辑,可选 false ‘click’ ‘dblclick’ | string | click |
FAQ
在 showLine 时,如何隐藏子节点图标?
文件图标通过 switcherIcon 来实现,如果不需要你可以覆盖对应的样式