Element ui menu tabs 菜单与标签页联动
页面
<el-container>
<el-aside :width="isCollapse ? '66px' : '200px'">
<!--左侧菜单区域-->
<el-menu router unique-opened :collapse="isCollapse" :collapse-transition="false" :default-active="activePath" class="menuLeft">
<button class="btnMenu" @click="toggleCollapse"><i class="el-icon-s-unfold"></i></button>
<el-submenu :index="index+''" v-for="(item,index) in routes" :key="index">
<template slot="title">
<i :class="item.iconCls" class="iconSty"></i>
<span class="iconStyle">{{item.name}}</span>
</template>
<el-menu-item :index="child.path" v-for="(child,indexJ) in item.children" :key="indexJ" @click="saveNavState(child.name,child.path)">
<i :class="child.iconCls" class="iconSty"></i>
{{child.name}}
</el-menu-item>
</el-submenu>
</el-menu>
</el-aside>
<el-main>
<el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab" @tab-click="btnSwitch">
<el-tab-pane
v-for="(item) in editableTabs"
:key="item.name"
:label="item.title"
:name="item.name"
>
<keep-alive>
<router-view/>
</keep-alive>
</el-tab-pane>
</el-tabs>
</el-main>
</el-container>
主要是这句
<keep-alive> // 这个标签就是缓存当前的内容 切换tabs的时候 不会丢失里面的内容
<router-view/>
</keep-alive>
点击左侧菜单
saveNavState (name, url) {
this.addTab(name, url) // 调用增加 tabs 标签页方法
this.activePath = url // 左侧菜单增加高亮
},
addTab (name, path) {
const that = this
// 去重,避免打开多个相同的标签页
if (that.editableTabs.findIndex(item => item.name === path) === -1) {
that.editableTabs.push({
title: name, // 标签页的名字
name: path, // 路由地址 /sys/user
content: path // 这没啥用 没删就留着了
})
}
this.editableTabsValue = path // 打开新的标签页
},
关闭标签页
removeTab (targetName) {
// 我的第一个页面是欢迎页 所以不想它被关掉
if (targetName === '/welcome') {
return
}
const tabs = this.editableTabs
let activeName = this.editableTabsValue
if (activeName === targetName) {
tabs.forEach((tab, index) => {
if (tab.name === targetName) {
const nextTab = tabs[index + 1] || tabs[index - 1]
if (nextTab) {
activeName = nextTab.name
}
}
})
}
this.editableTabsValue = activeName
this.$router.push(activeName) // 切换路由
this.activePath = activeName // 同步高亮
this.editableTabs = tabs.filter(tab => tab.name !== targetName)
},
点击tabs标签 切换
btnSwitch (r, e) {
this.$router.push(r.name) // 切换路由
this.activePath = r.name // 同步高亮
},
附上一张图片
![](https://img-blog.csdnimg.cn/b50c17181a41448bbf531b2c1dbb7399.png#pic_center