vue3+ts+elementui-plus二次封装树形表格实现不同层级展开收起的功能
<template>
<el-tree
:data="treeData"
:props="defaultProps"
:expand-on-click-node="false"
@node-click="handleNodeClick"
>
<template #default="{ node, data }">
<div class="custom-tree-node">
<span>{{ node.label }}</span>
<span>
<el-button v-if="data.children && data.children.length" type="text" @click="() => handleExpandClick(node)">
{{ node.expanded ? '收起' : '展开' }}
</el-button>
</span>
</div>
</template>
</el-tree>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { ElTree } from 'element-plus';
export default defineComponent({
components: {
ElTree,
},
setup() {
const treeData = ref([{
id: 1,
label: '一级目录 1',
children: [{
id: 4,
label: '二级目录 1-1',
}],
}]);
const defaultProps = {
children: 'children',
label: 'label',
};
const handleExpandClick = (node: any) => {
if (node.childNodes.length === 0) return;
if (node.expanded) {
ElTree.methods.collapseNode(node);
} else {
ElTree.methods.expandNode(node);
}
};
const handleNodeClick = (data: any, node: any, component: any) => {
console.log(data, node, component);
};
return {
treeData,
defaultProps,
handleExpandClick,
handleNodeClick,
};
},
});
</script>
<style>
.custom-tree-node {
flex: 1;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
padding-right: 8px;
}
</style>
这个代码实例展示了如何在Vue 3和Element Plus中使用树形表格组件,并且通过二次封装来实现点击按钮控制节点的展开和收起功能。这里使用了el-tree
组件的default
插槽来自定义节点内容,并通过按钮点击事件来调用ElTree.methods.expandNode
和ElTree.methods.collapseNode
方法来控制节点的展开和收起。
评论已关闭