100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > el-menu设置侧边栏使选项默认高亮与当前网址一致

el-menu设置侧边栏使选项默认高亮与当前网址一致

时间:2023-10-14 19:21:41

相关推荐

el-menu设置侧边栏使选项默认高亮与当前网址一致

el-element组件库中的el-menu组件用来做侧边栏导航非常方便

我在做vue后台管理系统项目时,侧边栏导航选用了右边这种布局

可以发现初始页面路径为'/home/,也就是主页,侧边栏也因此对应着高亮“首页”选项。此外选择其他选项,也能对应着跳转到目标路径,同时高亮对应侧边栏选项。

具体设置代码如下:

<template><el-menu:default-active="this.$route.path"class="el-menu-vertical-demo"@open="handleOpen"@close="handleClose":collapse="isCollapse"background-color="#545c64"text-color="#fff"active-text-color="#ffd04b"><h3 class="menu-title">{{isCollapse ? '后台' :'通用后台管理系统'}}</h3><el-menu-itemv-for="item in noChilderen":index="item.path === '/' ? '/home' : item.path" :key="item.path"@click="clickMenu(item)">//此处index设置稍有不同,是因为我路由设置里用了重定向,让'/'路径重定向到'/home'路径,这就使得我事先获取的数据中的'/'路径无法和默认跳转的'/home'相匹配,故有此设置<i :class="'el-icon-'+item.icon"></i><span slot="title">{{item.label}}</span></el-menu-item><el-submenu v-for="item in hasChilderen" :index="item.path+''" :key="item.path"><template slot="title"><i :class="'el-icon-'+item.icon"></i><span slot="title">{{item.label}}</span></template><el-menu-item-group v-for="(subItem) in item.children" :key=subItem.path><el-menu-item :index="subItem.path" @click="clickSubMenu(subItem)">{{subItem.label}}</el-menu-item></el-menu-item-group></el-submenu></el-menu></template>

computed: {//对获取的数据进行处理,分割出无子菜单和有子菜单的两组数据noChilderen () {return this.asyncMenu.filter(value => !value.children)},hasChilderen () {return this.asyncMenu.filter(value => value.children)},//menus是否折叠判断设置函数,与此侧边栏功能实现关系不大isCollapse () {return this.$store.state.tab.isCollapse},asyncMenu () {return this.$store.state.tab.menu//从vuex中获取数据}},

methods: {handleOpen (key, keyPath) {console.log(key, keyPath)},handleClose (key, keyPath) {console.log(key, keyPath)},//点击侧边栏的选项触发对应页面的跳转事件clickMenu (item) {this.$router.push({ path: item.path })//同步跳转生成tab栏,与此侧边栏功能实现关系不大this.selectMenu(item)},clickSubMenu (subItem) {this.$router.push({ path: subItem.path })this.selectMenu(subItem)},//导入vuex中的selectMenu函数...mapMutations(['selectMenu'])},

我是利用v-for循环来生成侧边栏,其中noChilderen是没有子菜单的数据组,hasChildren则是有子菜单的数据组,它们都事先获取了相关的path,name和其他一些属性,具体应用可以根据自己的实际需要进行修改。

其中比较关键的属性设置el-menu中的‘default-active’,这个属性就是当前处于激活状态选项栏的index,只要生成的el-menu-item中的index属性与其匹配上就把此选项高亮。

所以只需要把el-menu中的‘default-active’设置为当前网址的路径,即this.$route.path,然后把el-menu-item中的index属性设置为该选项对应的路由路径,就能实现页面跳转后,侧边栏对应选项高亮。

子级菜单也是一样,只要把子级菜单的路径配置给对应el-menu-item的index属性,也能实现相同功能。

参考文档:Element - The world's most popular Vue UI framework

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。