Element-ui 导航菜单Menu Methods与Menu Events的踩坑日记及解决方案
Element ui中Nav Menu 导航菜单关闭指定sub menu
仅供参考
自我记录.项目最初的想法是省略首页/的菜单配置 默认是首页 但当使用面包屑跳转到 首页的时候 路由切换回去菜单没有合并
下面是示例图

此时想到的解决方案是 监听路由变化 this.$route.path === '/' 的时候 调用elm组件事件 关闭菜单 这是错误的 此处有坑
element 组件说明示例图如下
比较坑的就是 element ui的事件是通过@close="xxx"触发
错误用法 踩坑此时调用成功但是不生效
<el-menu
router
:collapse="!isCollapse"
:collapse-transition="false"
background-color="#002033"
:default-active="$route.path"
class="el-menu-vertical-demo"
@open="handleOpen"
@close="handleClose"
text-color="#fff"
active-text-color="#ffd04b"
unique-opened>
</el-menu>
watch: {
$route () {
console.log(this.$route.path)
if (this.$route.path === '/') {
//当路径为首页的时候 关闭此时打开的menu
this.handleClose(this.KeyIndex)
}
}
},
methods: {
// sub-menu 展开的拿到index
handleOpen (key) {
console.log('我是打开index', key)
this.KeyIndex = key
},
// 使用index 关闭指定的sub-menu
handleClose (key) {
console.log(key)
}
}
正确方法
接下来看一下 element 的 方法调用是要绑定ref="menu"
<el-menu
ref="menu"
router
:collapse="!isCollapse"
:collapse-transition="false"
background-color="#002033"
:default-active="$route.path"
class="el-menu-vertical-demo"
@open="handleOpen"
@close="handleClose"
text-color="#fff"
active-text-color="#ffd04b"
unique-opened>
</el-menu>
watch: {
$route () {
console.log(this.$route.path)
if (this.$route.path === '/') {
this.$refs.menu.close(this.KeyIndex)
}
}
},
methods: {
handleOpen (key) {
console.log('我是打开index', key)
this.KeyIndex = key
}
}
组件方法使用说明

最后效果图

整体概括:监听路由-关闭菜单 思路是对的 但是要记得闭坑方法与事件使用的区别
!!!最后emelent组件事件的用法是@去绑定的 而方法是通过ref操作的望大家谨记不要犯和我一样的错误!!!

本文记录了在Element-UI中遇到的NavMenu导航菜单问题,即在面包屑跳转到首页时,菜单未合并。尝试通过监听路由并调用`handleClose`事件关闭子菜单失败,原因是错误地使用了组件方法。解决方案是通过给`el-menu`添加`ref=menu`,然后在路由变更时使用`this.$refs.menu.close()`来关闭指定子菜单。注意,组件事件是通过`@`绑定,而方法需通过`ref`调用。
1159





