主题
RNTreePanel 树形面板组件
组件介绍
RNTreePanel 是一个树形结构展示组件,基于 Naive UI 的 NTree 封装,支持异步加载、搜索过滤、拖拽等功能。
基础用法
使用ajax
数据多选
关联加载
Props
属性名 | 类型 | 默认值 | 说明 |
---|---|---|---|
data | Array | [] | 树形数据源 |
ajax | Function | null | 异步加载数据的函数 |
checkable | boolean | false | 是否显示复选框 |
selectable | boolean | true | 节点是否可选择 |
draggable | boolean | false | 是否允许拖拽 |
expandOnClick | boolean | false | 是否点击节点时展开 |
filterByLabel | boolean | true | 是否根据标签过滤 |
showLine | boolean | false | 是否显示连接线 |
immediate | boolean | true | 是否在组件加载时立即请求数据 |
数据项格式
每个树节点对象应包含以下字段:
key
(string | number): 节点的唯一标识label
(string): 节点显示的文本children
(Array, 可选): 子节点数组disabled
(boolean, 可选): 是否禁用该节点
事件说明
事件名 | 说明 | 回调参数 |
---|---|---|
select | 节点被选中时触发 | (keys: Array, nodes: Array) |
check | 节点被勾选时触发 | (keys: Array, nodes: Array) |
expand | 节点展开/收起时触发 | (keys: Array, nodes: Array) |
dragend | 拖拽结束时触发 | (info: Object) |
load | 异步加载完成时触发 | (node: Object) |
插槽
插槽名 | 说明 |
---|---|
default | 自定义节点内容 |
empty | 无数据时的内容 |
prefix | 节点前缀内容 |
suffix | 节点后缀内容 |
使用示例
基础用法
vue
<template>
<rn-tree-panel :data="treeData" checkable selectable @select="handleSelect" />
</template>
<script setup>
import { ref } from 'vue';
const treeData = ref([
{
key: '1',
label: '节点1',
children: [
{ key: '1-1', label: '子节点1' },
{ key: '1-2', label: '子节点2' },
],
},
{
key: '2',
label: '节点2',
},
]);
const handleSelect = (keys, nodes) => {
console.log('Selected:', keys, nodes);
};
</script>
异步加载
vue
<template>
<rn-tree-panel
:ajax="loadTreeData"
:expand-on-click="true"
:immediate="true"
/>
</template>
<script setup>
const loadTreeData = async (node) => {
// 模拟异步请求
const response = await fetch(
`/api/tree-nodes?parentId=${node?.key || 'root'}`,
);
return await response.json();
};
</script>
自定义节点内容
vue
<template>
<rn-tree-panel :data="treeData">
<template #default="{ node }">
<div class="custom-node">
<span>{{ node.label }}</span>
<n-button size="small" @click="handleAction(node)"> 操作 </n-button>
</div>
</template>
</rn-tree-panel>
</template>
注意事项
- 数据源中的节点必须包含唯一的key和label属性
- 使用异步加载时,需要正确处理loading状态
- 拖拽功能需要注意数据结构的完整性
- 大数据量时建议使用虚拟滚动优化性能
- ajax函数必须返回符合节点格式的数据数组