- 树形控件
- 何时使用
- 代码演示
- 受控操作示例
- 基本用法
- 自定义图标
- 拖动示例
- 异步数据加载
- 连接线
- 可搜索
- 目录
- API
- Tree props
- 事件
- TreeNode props
- DirectoryTree props
树形控件
何时使用
文件夹、组织架构、生物分类、国家地区等等,世间万物的大多数结构都是树形结构。使用树控件
可以完整展现其中的层级关系,并具有展开收起选择等交互功能。
代码演示
受控操作示例
受控操作示例
<template>
<a-tree
checkable
@expand="onExpand"
:expandedKeys="expandedKeys"
:autoExpandParent="autoExpandParent"
v-model="checkedKeys"
@select="onSelect"
:selectedKeys="selectedKeys"
:treeData="treeData"
/>
</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>
基本用法
最简单的用法,展示可勾选,可选中,禁用,默认展开等功能。
<template>
<a-tree
checkable
:treeData="treeData"
:defaultExpandedKeys="['0-0-0', '0-0-1']"
:defaultSelectedKeys="['0-0-0', '0-0-1']"
:defaultCheckedKeys="['0-0-0', '0-0-1']"
@select="this.onSelect"
@check="this.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>
自定义图标
可以针对不同的节点定制图标。
<template>
<a-tree
:treeData="treeData"
showIcon
defaultExpandAll
:defaultSelectedKeys="['0-0-0']"
>
<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>
拖动示例
将节点拖拽到其他节点内部或前后。
<template>
<a-tree
class="draggable-tree"
:defaultExpandedKeys="expandedKeys"
draggable
@dragenter="onDragEnter"
@drop="onDrop"
:treeData="gData"
/>
</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>
<a-tree
:loadData="onLoadData"
:treeData="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>
<a-tree
showLine
:defaultExpandedKeys="['0-0-0']"
@select="onSelect"
>
<a-tree-node key="0-0">
<span slot="title" style="color: #1890ff">parent 1</span>
<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 title="parent 1-1" key="0-0-1">
<a-tree-node title="leaf" key="0-0-1-0" />
</a-tree-node>
<a-tree-node title="parent 1-2" key="0-0-2">
<a-tree-node title="leaf" key="0-0-2-0" />
<a-tree-node title="leaf" key="0-0-2-1" />
</a-tree-node>
</a-tree-node>
</a-tree>
</template>
<script>
export default {
methods: {
onSelect (selectedKeys, info) {
console.log('selected', selectedKeys, info)
},
},
}
</script>
可搜索
可搜索的树。
<template>
<div>
<a-input-search style="margin-bottom: 8px" placeholder="Search" @change="onChange" />
<a-tree
@expand="onExpand"
:expandedKeys="expandedKeys"
:autoExpandParent="autoExpandParent"
:treeData="gData"
>
<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, node.key)
}
}
}
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.key.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>
目录
内置的目录树,multiple
模式支持 ctrl(Windows)
/ command(Mac)
复选。
<template>
<a-directory-tree
multiple
defaultExpandAll
@select="onSelect"
@expand="onExpand"
>
<a-tree-node title="parent 0" key="0-0">
<a-tree-node title="leaf 0-0" key="0-0-0" isLeaf />
<a-tree-node title="leaf 0-1" key="0-0-1" isLeaf />
</a-tree-node>
<a-tree-node title="parent 1" key="0-1">
<a-tree-node title="leaf 1-0" key="0-1-0" isLeaf />
<a-tree-node title="leaf 1-1" key="0-1-1" isLeaf />
</a-tree-node>
</a-directory-tree>
</template>
<script>
export default {
methods: {
onSelect (keys) {
console.log('Trigger Select', keys);
},
onExpand () {
console.log('Trigger Expand');
},
},
}
</script>
API
Tree props
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
treeData | 节点的配置描述,具体项见下表, 1.1.4之前的版本使用treeNodes | array | — |
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 |
selectedKeys(.sync) | (受控)设置选中的树节点 | string[] | number[] | - |
showIcon | 是否展示 TreeNode title 前的图标,没有默认样式,如设置为 true,需要自行定义图标相关样式 | boolean | false |
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 | - |
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' 'doubleclick' | string | click |