vue3 el-tree共用
时间: 2025-04-20 10:34:24 浏览: 24
### Vue3 中 `el-tree` 组件的共享或公用方法
在 Vue3 和 Element Plus 的环境中,为了实现 `el-tree` 组件的功能复用和代码优化,可以采用多种方式来创建可重用的方法。这些方法不仅限于特定页面或组件内部,而是可以在整个应用的不同部分调用。
#### 创建全局工具函数
通过定义一个独立的服务文件或者工具类,封装常用的树操作逻辑,如全选/取消全选、展开/折叠所有节点等。这种方式使得功能模块化,易于维护和测试。
```javascript
// src/utils/treeUtils.js
export function toggleAllSelection(treeRef, selected = true) {
const allNodes = treeRef.value.getCheckedKeys(false);
if (selected) {
treeRef.value.setCheckedKeys(allNodes.concat(treeRef.value.getHalfCheckedKeys()));
} else {
treeRef.value.setCheckedKeys([]);
}
}
export function collapseAll(treeRef) {
const nodes = treeRef.value.store._getAllNodes();
nodes.forEach(node => node.expanded = false);
}
```
此段代码展示了两个实用程序函数:一个是用于切换所有项的选择状态;另一个则是用来一次性关闭所有的分支[^1]。
#### 利用 Composition API 构建组合式函数
借助 Vue3 新引入的 Composition API 特性,能够更灵活地构建响应式的公共业务逻辑,并将其作为自定义 hook 提供给其他组件使用。
```typescript
import { ref, onMounted } from 'vue';
import { ElTree } from 'element-plus';
function useElTreeOperations() {
let treeInstance = ref<InstanceType<typeof ElTree> | null>(null);
const initTreeRef = (refValue: InstanceType<typeof ElTree>) => {
treeInstance.value = refValue;
};
const selectOrUnselectAll = () => {
if (!treeInstance.value) return;
const currentSelectedCount = treeInstance.value.getCheckedKeys().length;
const totalNodeCount = treeInstance.value.store._getAllNodes().filter(n => !n.isDisabled).length;
if (currentSelectedCount === totalNodeCount) {
// Unselect All
treeInstance.value.setCheckedKeys([]);
} else {
// Select All
treeInstance.value.setCheckedKeys(
treeInstance.value.store._getAllNodes()
.map(({ key }) => key)
.filter(key => !treeInstance.value.getNode(key)?.isDisabled),
);
}
};
onMounted(() => console.log('Tree operations initialized'));
return {
initTreeRef,
selectOrUnselectAll,
};
}
export default useElTreeOperations;
```
这段 TypeScript 代码片段提供了一个名为 `useElTreeOperations` 的 Hook 函数,它允许开发者轻松管理 `el-tree` 实例及其关联的操作,比如初始化引用以及执行批量选择动作[^2]。
#### 将常用配置提取至默认属性
对于那些频繁使用的参数设置(例如默认样式、事件监听器),可以通过扩展组件的方式预先设定好基础模板,减少重复编码的工作量。
```html
<!-- components/CommonTreeNode.vue -->
<template>
<el-tree :data="data" show-checkbox node-key="id"
highlight-current :props="defaultProps">
<!-- slot content here... -->
</el-tree>
</template>
<script setup lang="ts">
const props = defineProps({
data: Array as PropType<any[]>,
});
const defaultProps = reactive({
children: 'children',
label: 'label'
});
</script>
```
在此基础上,任何需要展示树形结构的地方都可以直接导入这个预设好的组件实例,而无需每次都重新声明相同的选项[^3]。
阅读全文
相关推荐
















