vue Element-ui NavMenu导航菜单Menu Methods与Menu Events的坑

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Element-ui 导航菜单Menu Methods与Menu Events的踩坑日记及解决方案


Element ui中Nav Menu 导航菜单关闭指定sub menu
仅供参考自我记录.

项目最初的想法是省略首页/的菜单配置 默认是首页 但当使用面包屑跳转到 首页的时候 路由切换回去菜单没有合并

下面是示例图
menus-bug
此时想到的解决方案是 监听路由变化 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操作的望大家谨记不要犯和我一样的错误!!!

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值