vue实现横向树
实现横向树的思路
横向树结构通常用于展示层级关系,但布局方向为水平而非传统的垂直方向。Vue中可以通过递归组件和CSS样式实现。
基础组件结构
创建递归组件HorizontalTree.vue,用于渲染树节点:
<template>
<div class="horizontal-tree">
<div class="node">
{{ node.name }}
</div>
<div
v-if="node.children && node.children.length"
class="children"
>
<HorizontalTree
v-for="child in node.children"
:key="child.id"
:node="child"
/>
</div>
</div>
</template>
<script>
export default {
name: 'HorizontalTree',
props: {
node: {
type: Object,
required: true
}
}
}
</script>
CSS样式设置
关键是通过Flex布局实现水平排列:
.horizontal-tree {
display: flex;
flex-direction: row;
align-items: center;
}
.node {
padding: 8px 12px;
margin: 0 10px;
border: 1px solid #ddd;
border-radius: 4px;
background: #f5f5f5;
}
.children {
display: flex;
position: relative;
}
.children::before {
content: "";
position: absolute;
top: 50%;
left: 0;
right: 0;
height: 1px;
background: #ccc;
z-index: -1;
}
使用组件
在父组件中传入树形数据:
<template>
<div>
<HorizontalTree :node="treeData" />
</div>
</template>
<script>
import HorizontalTree from './HorizontalTree.vue'
export default {
components: { HorizontalTree },
data() {
return {
treeData: {
id: 1,
name: 'Root',
children: [
{
id: 2,
name: 'Child 1',
children: [
{ id: 4, name: 'Grandchild 1' },
{ id: 5, name: 'Grandchild 2' }
]
},
{
id: 3,
name: 'Child 2'
}
]
}
}
}
}
</script>
高级优化
添加动画效果增强用户体验:
.node {
transition: all 0.3s ease;
}
.node:hover {
transform: scale(1.05);
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
实现动态展开/折叠功能:
<template>
<div class="horizontal-tree">
<div
class="node"
@click="toggle"
>
{{ node.name }}
<span v-if="hasChildren">
{{ isExpanded ? '−' : '+' }}
</span>
</div>
<div
v-if="isExpanded && hasChildren"
class="children"
>
<HorizontalTree
v-for="child in node.children"
:key="child.id"
:node="child"
/>
</div>
</div>
</template>
<script>
export default {
name: 'HorizontalTree',
props: {
node: {
type: Object,
required: true
}
},
data() {
return {
isExpanded: true
}
},
computed: {
hasChildren() {
return this.node.children && this.node.children.length
}
},
methods: {
toggle() {
if (this.hasChildren) {
this.isExpanded = !this.isExpanded
}
}
}
}
</script>
响应式设计
添加媒体查询确保在小屏幕上正常显示:

@media (max-width: 768px) {
.horizontal-tree {
flex-direction: column;
}
.children {
flex-direction: column;
}
.children::before {
width: 1px;
height: auto;
bottom: 0;
left: 50%;
top: 0;
}
}






