输出代码vue使用element ui 的导航组件实现点击头部一级菜单,侧边栏二三级菜单联动切换
时间: 2024-03-05 21:54:29 浏览: 51
vue2.0实现导航菜单切换效果
下面是一个简单的示例代码,演示了如何使用Vue和Element UI实现点击头部一级菜单,侧边栏二三级菜单联动切换的功能。
头部一级菜单组件:
```html
<template>
<el-menu mode="vertical">
<el-menu-item v-for="item in menuList" :key="item.name" @click="handleClick(item.name)">
{{ item.label }}
</el-menu-item>
</el-menu>
</template>
<script>
export default {
data() {
return {
menuList: [
{ name: 'dashboard', label: '仪表盘' },
{ name: 'product', label: '商品管理' },
{ name: 'order', label: '订单管理' }
]
}
},
methods: {
handleClick(name) {
this.$emit('menu-click', name)
}
}
}
</script>
```
侧边栏组件:
```html
<template>
<el-menu>
<el-submenu v-for="item in menuList" :key="item.name" :name="item.name">
<template slot="title">{{ item.label }}</template>
<el-menu-item v-for="subItem in item.children" :key="subItem.name">
{{ subItem.label }}
</el-menu-item>
</el-submenu>
</el-menu>
</template>
<script>
export default {
data() {
return {
menuList: [
{
name: 'dashboard',
label: '仪表盘',
children: [
{ name: 'realtime', label: '实时数据', parentName: 'dashboard' },
{ name: 'history', label: '历史数据', parentName: 'dashboard' }
]
},
{
name: 'product',
label: '商品管理',
children: [
{ name: 'list', label: '商品列表', parentName: 'product' },
{ name: 'add', label: '添加商品', parentName: 'product' }
]
},
{
name: 'order',
label: '订单管理',
children: [
{ name: 'list', label: '订单列表', parentName: 'order' },
{ name: 'detail', label: '订单详情', parentName: 'order' }
]
}
]
}
},
created() {
this.$on('menu-click', this.handleMenuClick)
},
methods: {
handleMenuClick(name) {
const menuItem = this.menuList.find(item => item.name === name)
if (menuItem) {
const subMenuNames = menuItem.children.map(item => item.parentName)
this.$emit('submenu-click', subMenuNames)
}
}
}
}
</script>
```
父组件:
```html
<template>
<div>
<Header @menu-click="handleMenuClick" />
<Sidebar @submenu-click="handleSubmenuClick" />
</div>
</template>
<script>
import Header from './Header.vue'
import Sidebar from './Sidebar.vue'
export default {
components: { Header, Sidebar },
methods: {
handleMenuClick(name) {
this.$refs.sidebar.$emit('menu-click', name)
},
handleSubmenuClick(names) {
this.$refs.sidebar.$emit('submenu-click', names)
}
}
}
</script>
```
在父组件中,监听Header组件的menu-click事件,获取到点击的菜单项的name字段,然后通过$refs属性获取到Sidebar组件的实例,调用$emit方法向Sidebar组件传递name字段,实现了头部一级菜单点击事件和侧边栏二三级菜单联动切换的功能。
阅读全文