vue左右联动菜单实现
实现思路
左右联动菜单通常由两个部分组成:左侧的分类菜单和右侧的内容列表。当点击左侧的分类项时,右侧会显示对应的内容。这种交互常见于电商网站的商品分类浏览。
数据结构设计
使用 Vue 实现时,通常需要一个嵌套的数据结构来表示分类和内容。例如:
data() {
return {
categories: [
{
id: 1,
name: '分类1',
items: [
{ id: 1, name: '商品1' },
{ id: 2, name: '商品2' }
]
},
{
id: 2,
name: '分类2',
items: [
{ id: 3, name: '商品3' },
{ id: 4, name: '商品4' }
]
}
],
activeCategoryId: 1
}
}
模板结构
在模板中,使用两个独立的容器分别渲染左侧菜单和右侧内容:
<div class="container">
<div class="left-menu">
<div
v-for="category in categories"
:key="category.id"
@click="activeCategoryId = category.id"
:class="{ active: activeCategoryId === category.id }"
>
{{ category.name }}
</div>
</div>
<div class="right-content">
<div v-for="item in activeItems" :key="item.id">
{{ item.name }}
</div>
</div>
</div>
计算属性
使用计算属性来获取当前选中分类对应的内容项:
computed: {
activeItems() {
const category = this.categories.find(c => c.id === this.activeCategoryId)
return category ? category.items : []
}
}
样式处理
添加基础样式使布局更清晰:
.container {
display: flex;
height: 100%;
}
.left-menu {
width: 200px;
border-right: 1px solid #eee;
}
.left-menu div {
padding: 10px;
cursor: pointer;
}
.left-menu div.active {
background-color: #f0f0f0;
font-weight: bold;
}
.right-content {
flex: 1;
padding: 10px;
}
优化交互
可以添加过渡动画增强用户体验:
<transition-group name="fade" tag="div" class="right-content">
<div v-for="item in activeItems" :key="item.id">
{{ item.name }}
</div>
</transition-group>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
响应式处理
对于移动端,可以添加响应式设计:
@media (max-width: 768px) {
.container {
flex-direction: column;
}
.left-menu {
width: 100%;
display: flex;
overflow-x: auto;
}
}
性能考虑
当数据量较大时,可以使用虚拟滚动优化性能:
<RecycleScroller
class="right-content"
:items="activeItems"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div>{{ item.name }}</div>
</RecycleScroller>
需要先安装 vue-virtual-scroller 插件:
npm install vue-virtual-scroller






