点击菜单栏新开标签页
需求描述
朋友在工作中遇到这么一个需求来问我,简单记录下。如题,她需要点击左侧菜单栏时,不是正常的在系统中显示页面内容,而是新开一个没有菜单栏只有主体页面新标签页。新开标签之后,菜单高亮显示部分是刚点击的,与实际显示页面对不上,需解决。
问题解决
首先是实现点击目录之后,旧页面路由不变,在新页面中打开。实现代码如下:
路由不变,新开页面
法1
<!-- 对应带单目录处添加select函数,处理点击事件 -->
<el-menu
:default-active="$route.path"
:collapse="isCollapse"
:background-color="sideBarBg"
:text-color="variables.menuText"
:active-text-color="font()"
mode="vertical"
@select="select"
>
<sidebar-item
v-for="route in routers"
:key="route.path"
class="left-menu"
:item="route"
:base-path="route.path"
/>
</el-menu>
select(key, keyPath) {
if (key === '/directory/activity') {
window.open(this.$router.resolve('activity').href)
// 此处的key为你需要跳转的路由时,新开页面,activity为你在路由router文件中设置的path
}
}
// 同时如果项目是使用的某个github开源项目改的,侧边栏Sidebar文件夹中应该有个link文件,更改其中函数
linkProps(url) {
if (isExternal(url)) {
return {
is: 'a',
href: url,
target: '_blank',
rel: 'noopener'
}
}
if (url === '/directory/activity') {
// 添加此处判断,避免旧页面发生路由跳转
return {
is: 'div'
}
}
return {
is: 'router-link',
to: url
}
}
法2
仔细想之后,好像不用使用window.open,直接更改router-link为a标签就好了。只改link中函数:
linkProps(url) {
if (isExternal(url)) {
return {
is: 'a',
href: url,
target: '_blank',
rel: 'noopener'
}
}
if (url === '/directory/activity') {
return {
is: 'a',
href: this.$router.resolve('activity').href,
target: '_blank',
rel: 'opener' // 使用opener才能使用旧页面的sessionStorage,如不需要请设为noopener,可减少安全问题
}
}
return {
is: 'router-link',
to: url
}
}
菜单高亮与实际页面对应
通过设置el-menu中的default-active(无效)和el-menu-item中的index(会有多个高亮菜单)效果都不佳。但想到el-menu中肯定会有某个变量控制高亮显示的,因此去阅读其对应源码后,得知次变量为activeIndex,尝试通过绑定ref的方式在点击后手动更改。成功生效。代码如下:
<el-menu
ref="elmenu"
:default-active="$route.path"
:collapse="isCollapse"
:background-color="sideBarBg"
:text-color="variables.menuText"
:active-text-color="font()"
mode="vertical"
@select="select"
>
<sidebar-item
v-for="route in routers"
:key="route.path"
class="left-menu"
:item="route"
:base-path="route.path"
/>
</el-menu>
select(key, keyPath) {
if (key === '/directory/activity') {
window.open(this.$router.resolve('activity').href) // 如果使用a标签,则不需要此行
this.$refs.elmenu.activeIndex = this.$route.path // 将高亮重新设定为当前路由对应菜单
}
},
