Ant-design-vue vue3树形控件tree 新增节点,删除节点,
时间: 2023-08-16 19:09:14 浏览: 252
tree 节点 添加 删除
在Vue3中,Ant-Design-Vue的Tree组件的用法与Vue2有些不同。以下是示例代码:
```html
<template>
<a-tree :tree-data="treeData" :draggable="true" :block-node="true" :show-line="true" :default-expanded-keys="defaultExpandedKeys" v-model:selected-keys="selectedKeys" @select="onSelect">
<template #title="{ key, title }">
<span>
{{ title }}
<a @click.stop="addNode(key)">Add</a>
<a @click.stop="removeNode(key)">Delete</a>
</span>
</template>
</a-tree>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const treeData = ref([
{
title: 'Parent 1',
key: '0-0',
children: [
{
title: 'Child 1',
key: '0-0-0'
},
{
title: 'Child 2',
key: '0-0-1'
}
]
}
])
const defaultExpandedKeys = ref(['0-0'])
const selectedKeys = ref([])
const addNode = (parentKey) => {
const newNode = { title: 'New Node', key: `${parentKey}-${treeData.value.length}` }
const parentNode = treeData.value.find(node => node.key === parentKey)
if (!parentNode.children) {
parentNode.children = []
}
parentNode.children.push(newNode)
treeData.value = [...treeData.value]
}
const removeNode = (key) => {
const parentKey = key.split('-').slice(0, -1).join('-')
const parentNode = treeData.value.find(node => node.key === parentKey)
parentNode.children = parentNode.children.filter(node => node.key !== key)
treeData.value = [...treeData.value]
}
const onSelect = (selectedKeys) => {
console.log(selectedKeys)
}
return {
treeData,
defaultExpandedKeys,
selectedKeys,
addNode,
removeNode,
onSelect
}
}
}
</script>
```
这个示例与Vue2中的示例类似,只是我们使用了Vue3的Composition API来编写代码。我们使用了ref函数来创建响应式变量。在addNode和removeNode方法中,我们使用了Vue3的响应式API来更新数据。当我们改变treeData的值时,我们必须通过解构赋值来创建一个新的数组来触发更新。注意,在Vue3中,我们使用v-model来绑定selected-keys。
阅读全文