Ant design 组件库中的树形控件,展示了相关的数据展示用法,但基本的增删改查操作还需要自己实现以下,最近花了两三天将基本操作进行实现了。(因为我很菜)
控件基本用法
首先,在组件库的基础上进行树形控件的搭建,引入组件库这一步(Ant design官网就有),下面进行介绍。
选择Tree控件的一类简单的进行使用,最重要的就是要看清楚其中的树形控件的数据定义,要求是树形的数据,在所给代码中就是treeData(treeData定义为响应式,我认为还是定义为reactive比较好);

<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']"
:tree-data="treeData"
@select="onSelect"
>
<template #icon><carry-out-outlined /></template>
<template #title="{ dataRef }">
<template v-if="dataRef.key === '0-0-0-1'">
<div>multiple line title</div>
<div>multiple line title</div>
</template>
<template v-else>{
{
dataRef.title }}</template>
</template>
<template #switcherIcon="{ dataRef, defaultIcon }">
<SmileTwoTone v-if="dataRef.key === '0-0-2'" />
<component :is="defaultIcon" v-else />
</template>
</a-tree>
</div>
</template>
<script>
import {
CarryOutOutlined, SmileTwoTone } from '@ant-design/icons-vue';
import {
defineComponent, ref } from 'vue';
export default defineComponent({
components: {
CarryOutOutlined,
SmileTwoTone,
},
setup() {
const showLine = ref(true);
const showIcon = ref(false);
const treeData = ref([{
title: 'parent 1',
key: '0-0',
children: [{
title: 'parent 1-0',
key: '0-0-0',
children: [{
title: 'leaf',
key: '0-0-0-0',
}, {
key: '0-0-0-1',
}, {
title: 'leaf',
key: '0-0-0-2',
}],
}, {
title: 'parent 1-1',
key: '0-0-1',
children: [{
title: 'leaf',
key: '0-0-1-0',
}],
}, {
title: 'parent 1-2',
key: '0-0-2',
children: [{
title: 'leaf 1',
key: '0-0-2-0',
}, {
title: 'leaf 2',
key: '0-0-2-1',
}],
}],
}, {
title: 'parent 2',
key: '0-1',
children: [{
title: 'parent 2-0',
key: '0-1-0',
children: [{
title: 'leaf',
key: '0-1-0-0',
}, {
title: 'leaf',
key: '0-1-0-1',
}],
}],
}]);
const onSelect = (selectedKeys, info) => {
console.log('selected', selectedKeys, info);
};
return {
showLine,
showIcon,
onSelect,
treeData,
};
},
});
</script>
基本的效果就能展示到页面上了,其中的各个api,方法等在antdev的下面都有详细的说明。已经能自由进行展开和折叠,以及是否展示连线或者切换图标。
下面先做一个基本的功能,一个switch开关实现,全部展开和折叠。
- step1:在template中将样式写进去
<a-switch v-model:checked="allKinds"/>
其中的allkinds就是开关绑定的响应式变量,当checked变化时执行函数
- step2:将定义的函数写在script的setup中,并返回出去,这里watch变量allkinds的变化

本文介绍了如何在Vue项目中使用Ant Design的Tree组件进行增删改查操作。首先讲解了控件的基本用法,包括数据定义和基本展示效果。接着详细阐述了搜索、编辑、新增和删除四个功能的实现步骤。编辑功能通过监听selectedKeys并修改treeData实现,新增和删除则是通过对父节点children的操作来完成。整个过程充分利用了Ant Design Tree组件的API和Vue的响应式特性。
最低0.47元/天 解锁文章
1090

被折叠的 条评论
为什么被折叠?



