vue实现左右菜单
Vue 实现左右菜单
使用 Vue Router 和组件结构
创建一个基本的 Vue 项目结构,包含左右菜单组件和主内容区域。通过 Vue Router 实现路由跳转。
<template>
<div class="app-container">
<div class="left-menu">
<ul>
<li v-for="item in leftMenuItems" :key="item.path">
<router-link :to="item.path">{{ item.name }}</router-link>
</li>
</ul>
</div>
<div class="right-menu">
<ul>
<li v-for="item in rightMenuItems" :key="item.path">
<router-link :to="item.path">{{ item.name }}</router-link>
</li>
</ul>
</div>
<div class="main-content">
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
data() {
return {
leftMenuItems: [
{ path: '/left1', name: '左侧菜单1' },
{ path: '/left2', name: '左侧菜单2' }
],
rightMenuItems: [
{ path: '/right1', name: '右侧菜单1' },
{ path: '/right2', name: '右侧菜单2' }
]
}
}
}
</script>
<style>
.app-container {
display: flex;
height: 100vh;
}
.left-menu, .right-menu {
width: 200px;
background: #f0f0f0;
padding: 20px;
}
.main-content {
flex: 1;
padding: 20px;
}
ul {
list-style: none;
padding: 0;
}
li {
margin-bottom: 10px;
}
</style>
动态菜单与状态管理
对于更复杂的场景,可以使用 Vuex 管理菜单状态,实现动态菜单加载和权限控制。
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
leftMenu: [],
rightMenu: []
},
mutations: {
SET_MENUS(state, { left, right }) {
state.leftMenu = left
state.rightMenu = right
}
},
actions: {
async fetchMenus({ commit }) {
// 模拟API调用
const left = await getLeftMenu()
const right = await getRightMenu()
commit('SET_MENUS', { left, right })
}
}
})
// 组件中使用
export default {
computed: {
leftMenuItems() {
return this.$store.state.leftMenu
},
rightMenuItems() {
return this.$store.state.rightMenu
}
},
created() {
this.$store.dispatch('fetchMenus')
}
}
响应式布局
添加响应式设计,在小屏幕设备上隐藏一侧菜单或改为折叠式菜单。
@media (max-width: 768px) {
.right-menu {
display: none;
}
.left-menu {
width: 60px;
overflow: hidden;
}
.left-menu:hover {
width: 200px;
}
}
动画过渡效果
为菜单项添加过渡动画,提升用户体验。
<transition-group name="menu-item" tag="ul">
<li v-for="item in leftMenuItems" :key="item.path">
<router-link :to="item.path">{{ item.name }}</router-link>
</li>
</transition-group>
<style>
.menu-item-enter-active, .menu-item-leave-active {
transition: all 0.5s;
}
.menu-item-enter, .menu-item-leave-to {
opacity: 0;
transform: translateX(-30px);
}
</style>
嵌套路由配置
配置嵌套路由以匹配菜单结构,确保路由与菜单项同步。
const router = new VueRouter({
routes: [
{
path: '/left',
component: LeftContainer,
children: [
{ path: 'left1', component: Left1 },
{ path: 'left2', component: Left2 }
]
},
{
path: '/right',
component: RightContainer,
children: [
{ path: 'right1', component: Right1 },
{ path: 'right2', component: Right2 }
]
}
]
})






