vue实现左右菜单
实现左右菜单的Vue方案
使用Vue Router与嵌套路由
在router/index.js中配置嵌套路由结构,主布局包含左右两个区域:
{
path: '/',
component: MainLayout,
children: [
{
path: '',
components: {
left: LeftMenu,
right: ContentArea
}
}
]
}
主布局组件使用命名视图:
<div class="main-layout">
<div class="left-menu">
<router-view name="left"></router-view>
</div>
<div class="right-content">
<router-view name="right"></router-view>
</div>
</div>
基于组件通信的实现
创建父组件管理状态:
export default {
data() {
return {
activeMenu: 'home'
}
}
}
左侧菜单组件发射事件:

<ul class="menu-list">
<li @click="$emit('menu-change', 'home')">首页</li>
<li @click="$emit('menu-change', 'products')">产品</li>
</ul>
右侧内容组件接收prop:
props: ['currentMenu'],
watch: {
currentMenu(newVal) {
this.loadContent(newVal)
}
}
使用Vuex状态管理
store模块定义:

const store = new Vuex.Store({
state: {
activeMenu: null
},
mutations: {
SET_MENU(state, menu) {
state.activeMenu = menu
}
}
})
菜单组件提交变更:
methods: {
selectMenu(menu) {
this.$store.commit('SET_MENU', menu)
}
}
响应式布局样式
基础CSS结构:
.main-layout {
display: flex;
height: 100vh;
}
.left-menu {
width: 250px;
background: #f5f5f5;
transition: all 0.3s;
}
.right-content {
flex: 1;
overflow: auto;
}
@media (max-width: 768px) {
.left-menu {
width: 60px;
}
}
动态菜单实现示例
递归组件实现多级菜单:
Vue.component('menu-item', {
template: `
<li>
<div @click="toggle">
{{ item.name }}
</div>
<ul v-show="isOpen" v-if="item.children">
<menu-item
v-for="child in item.children"
:item="child"
:key="child.path"
></menu-item>
</ul>
</li>
`,
props: ['item'],
data() {
return {
isOpen: false
}
},
methods: {
toggle() {
this.isOpen = !this.isOpen
}
}
})






