![在这里插入图片描述](https://img-blog.csdnimg.cn/9a1def1477ee4c4a8c4bfd5ab80356d8.png)
<el-tabs v-model="activeTab" type="border-card" @tab- remove="removeTab">
<el-tab-pane
:key="item.name"
v-for="item in editableTabs"
:label="item.title"
:closable="item.closable"
:name="item.name"
:ref="item.path"
:lazy="true">
<component :is="item.content"></component>
</el-tab-pane>
一、循环渲染导航菜单menu
二、先定义一个默认的tabs,比如首页
editableTabs: [
{
title: '首页',
name: '/welcome1',
content: welcome,
path: '/welcome',
},
],
三、实现点击菜单往editableTabs数组中追加
1、使用watch监听路由变化
watch: {
//观察路由变化
$route: {
handler(v) {
this.openPage(v);
},
immediate: true,
},
},
2、 拿到该路由信息进行push操作tabs
openPage(route) {
const path = route.path; //拿到路由名称
if (Object.keys(route.meta).length != 0) {
//meta里是名称和卡片内容
const thisName = route.meta.title;
const thisComp = route.meta.comp;
let newActiveIndex = path + ++this.tabIndex; //tabIndex默认是1,该变量结果是/customerList3
//如果有重复的就不去push
for (let i = 0; i < this.editableTabs.length; i++) {
if (this.editableTabs[i].title == route.meta.title) {
this.editableTabs.splice(i, 1, {
title: thisName,
name: String(newActiveIndex),
content: thisComp,
path: path,
});
this.activeTab = newActiveIndex;
return;
}
}
//拿到该路由后进行push
this.editableTabs.push({
title: thisName,
name: String(newActiveIndex),
content: thisComp,
path: path,
});
this.activeTab = newActiveIndex; //activeTab是tabs是双向绑定,默认选中是首页
}
}
四、实现删除tabs
removeTab(targetName) {
//targetName是删除标签的name
let tabs = this.editableTabs; //tabs数组
let activeName = this.activeTab; //tabs是双向绑定,选中值
if (activeName === targetName){
tabs.forEach((tab, index) => {
if (tab.name === targetName){
let nextTab = tabs[index + 1] || tabs[index - 1];
if (nextTab) {
activeName = nextTab.name;
}
//首页不可以删
if (tabs.length == 2) {
this.$router.push({
path: '/welcome',
});
}
}
})
}
this.editableTabsValue = activeName;
this.editableTabs = tabs.filter(tab => tab.name !== targetName);
}