注意 this.$refs.tabs[i] 的属性对应
<template>
<el-tabs v-model="activeTab" type="card"
@tab-remove="removeTab" @tab-click="tabClick">
<el-tab-pane v-for="(item, index) in tabsItem"
:key="item.name"
:label="item.title"
:name="item.name"
:closable="item.closable"
:ref="item.ref">
</el-tab-pane>
</el-tabs>
</template>
<script>
export default {
name: "Tabs",
data() {
return {
activeTab: '1',
tabIndex: 1,
tabsItem: [{
title: '库存预警',
name: '1',
closable: false,
ref: 'tabs',
}],
tabsPath: [{
name: "1",
path: '/index'
}]
}
},
watch: {
'$route': function (to) {
let flag = true;
const path = to.path;
if (Object.keys(to.meta).length !== 0) {
for (let i = 0; i < this.$refs.tabs.length; i++) {
if (this.$refs.tabs[i].label === to.meta.title) {
this.activeTab = this.$refs.tabs[i].name;
flag = false;
break;
}
}
if (flag) {
const thisName = to.meta.title
let newActiveIndex = ++this.tabIndex + '';
this.tabsItem.push({
title: thisName,
name: String(newActiveIndex),
closable: true,
ref: 'tabs',
})
this.activeTab = newActiveIndex;
if (this.tabsPath.indexOf(path) === -1) {
this.tabsPath.push({
name: newActiveIndex,
path: path
})
}
}
}
}
},
methods: {
removeTab(targetName) {
let tabs = this.tabsItem;
let activeName = this.activeTab;
if (activeName === targetName) {
tabs.forEach((tab, index) => {
if (tab.name === targetName) {
let nextTab = tabs[index + 1] || tabs[index - 1];
if (nextTab) {
activeName = nextTab.name;
this.tabClick(nextTab);
}
}
});
}
this.activeTab = activeName;
this.tabsItem = tabs.filter(tab => tab.name !== targetName);
this.tabsPath = this.tabsPath.filter(item => item.name !== targetName)
},
tabClick(thisTab) {
let val = this.tabsPath.filter(item => thisTab.name === item.name)
this.$router.push({
path: val[0].path
})
}
},
mounted() {
window.addEventListener('beforeunload', e => {
sessionStorage.setItem("tabsItem", JSON.stringify({
currTabsItem: this.tabsItem.filter(item => item.name !== "1"),
currTabsPath: this.tabsPath.filter(item => item.name !== "1"),
currActiveTabs: this.activeTab,
currIndex: this.tabIndex
}))
});
},
created() {
const sessionTabs = JSON.parse(sessionStorage.getItem("tabsItem"))
if (sessionTabs.currTabsItem.length !== 0 && sessionTabs.currTabsPath.length !== 0) {
for (let i = 0; i < sessionTabs.currTabsItem.length; i++) {
this.tabsItem.push({
title: sessionTabs.currTabsItem[i].title,
name: sessionTabs.currTabsItem[i].name,
closable: true,
ref: sessionTabs.currTabsItem[i].ref,
content: sessionTabs.currTabsItem[i].content
})
}
for (let j = 0; j < sessionTabs.currTabsPath.length; j++) {
this.tabsPath.push({
name: sessionTabs.currTabsPath[j].name,
path: sessionTabs.currTabsPath[j].path
})
}
this.activeTab = sessionTabs.currActiveTabs
this.tabIndex = sessionTabs.currIndex
const activePath = this.tabsPath.filter(item => item.name === this.activeTab)
this.$router.push({
path: activePath[0].path
})
}
},
}
</script>
<style scoped>
/deep/ .el-tabs__header {
margin: 0;
}
</style>