vue.js 树形
时间: 2023-07-18 19:04:20 浏览: 93
Vue.js 提供了许多开源组件库来构建树形结构。以下是一个基本的树形结构示例:
首先,我们需要一个组件来表示每个树节点:
```
<template>
<li>
{{ node.label }}
<ul v-if="node.children">
<tree-node
v-for="child in node.children"
:key="child.id"
:node="child"
/>
</ul>
</li>
</template>
<script>
export default {
name: "TreeNode",
props: {
node: {
type: Object,
required: true
}
},
components: {
TreeNode: this.$options.components.TreeNode
}
};
</script>
```
然后,我们需要一个组件来表示整个树:
```
<template>
<ul>
<tree-node
v-for="node in tree"
:key="node.id"
:node="node"
/>
</ul>
</template>
<script>
import TreeNode from "./TreeNode";
export default {
name: "Tree",
props: {
tree: {
type: Array,
required: true
}
},
components: {
TreeNode
}
};
</script>
```
现在我们可以使用这些组件来渲染树:
```
<template>
<div>
<h1>Tree</h1>
<Tree :tree="treeData" />
</div>
</template>
<script>
import Tree from "./Tree";
export default {
name: "App",
components: {
Tree
},
data() {
return {
treeData: [
{
id: 1,
label: "Node 1",
children: [
{
id: 2,
label: "Node 1.1",
children: [
{
id: 3,
label: "Node 1.1.1"
},
{
id: 4,
label: "Node 1.1.2"
}
]
},
{
id: 5,
label: "Node 1.2"
}
]
},
{
id: 6,
label: "Node 2",
children: [
{
id: 7,
label: "Node 2.1"
},
{
id: 8,
label: "Node 2.2"
}
]
}
]
};
}
};
</script>
```
这样就可以渲染一个简单的树形结构了。需要注意的是,这只是一个基本示例,实际项目中可能需要更多的交互和功能。
阅读全文