<el-tabs v-model="activeIndex" type="card" @tab-click="clickTab" @tab-remove="removeTab" closable>
<el-tab-pane v-for="item of openTab" v-show="openTab.length" :key="item.name" :label="item.name" :name="item.route" ></el-tab-pane>
</el-tabs>
思路:(本人不喜欢用vuex,所有数据写在一个页面里)
1. data里面要有一个openTab数组,用来存放跳转过的地址,还要有一个activeindex,当作激活当前的tabs栏;
2. 在mouted里面写代码,在判断1里面判断this.openTab.length是否小于0,再在判断1里面进行判断2当前路由如果不是首页,往openTab里面添加一个首页信息、一个当前路由信息,并设置this.activeindex为当前路由来激活tabs栏,判断2的else(即当前路由是首页),则openTab添加一个首页信息,并设置this.activeindex为首页
3. 监听路由,当路由跳转时,判断this.openTab是否有当前路由的信息,有则设置this.activeindex为当前路由来激活tabs栏,如果没有,则往this.openTab里面添加当前路由的信息,并且设置this.activeindex为当前路由来激活tabs栏
4. methods里面3个方法,一、删除tabs栏某一项(即删除this.openTab某一项数据),并激活this.openTab下一个路由信息的方法(removeTab);二、点击跳转时跳转路由(clickTab)
最后一点,耐心去理解代码,总会有所收获!
下面是代码:
<template>
<div>
<el-tabs
v-model="activeIndex"
type="card"
@tab-click="clickTab"
@tab-remove="removeTab"
closable
>
<!-- v-if可用v-show代替,也可考虑使用计算属性代替v-for与v-if功能 -->
<el-tab-pane
v-for="item of openTab"
v-if="openTab.length"
:key="item.name"
:label="item.name"
:name="item.route"
>
</el-tab-pane>
</el-tabs>
<router-view />
</div>
</template>
<script>
export default {
data(){
return {
openTab:[],
activeIndex:''
}
},
methods:{
set_active_index(index){
this.activeIndex = index
},
add_tabs(data){
this.openTab.push(data)
},
delete_tabs(route){
let index = 0
for(let gohh of this.openTab){
if(gohh.route == route){
break
}
index++
}
this.openTab.splice(index,1)
},
clickTab() {
this.$router.push({path: this.activeIndex})
console.log(this.$route.path)
},
removeTab (target) {
if(target == '/page1'){
return
}
this.delete_tabs(target)
if (this.activeIndex === target) {
if (this.openTab && this.openTab.length >= 1) {
console.log('=============', this.openTab[this.openTab.length - 1].route)
this.set_active_index(this.openTab[this.openTab.length - 1].route)
this.$router.push({path: this.activeIndex})
}
}
}
},
watch: {
'$route' (to, from) {
console.log('跳转了')
let flag = false
for (let item of this.openTab) {
if (item.name === to.name) {
this.set_active_index(to.path)
flag = true
break
}
}
if (!flag) {
this.add_tabs({route: to.path, name: to.name})
this.set_active_index(to.path)
}
}
},
mounted () {
console.log('mounted')
console.log('mounted1',this.openTab)
if(this.openTab.length>=1){
}else{
if(this.$route.path !== '/page1') {
console.log('mounted222222',this.openTab)
this.add_tabs({route: '/page1' , name: '商户信息'})
this.add_tabs({route: this.$route.path , name: this.$route.name })
this.set_active_index(this.$route.path)
}else{
this.add_tabs({route: '/page1', name: '商户信息'})
this.set_active_index('/page1')
}
}
}
}
</script>