仿element-ui tabs的路由组件
很喜欢element-ui的这个tab组件,但是这里设计应该是用来做html显示的切换,本来也考虑将组件直接放到这个tab内,切换tab显示不同组件,但是试了一下未激活的标签内容也会预先加载,不太友好。尝试将其改为路由的方式,发现太麻烦了,所以参照这个样式写了个支持路由的组件。
组件代码:
<template>
<div class="tab-container">
<template v-for="(tab, index) in tabList">
<span
class="tab-single"
:class="{ 'tab-active': index === activeIndex }"
:key="index"
@click="linkRouter(tab.tabRouter, index)"
>{{ tab.tabName }}</span
>
</template>
</div>
</template>
<script>
export default {
name: "SelfTab",
data() {
return {
activeIndex: 0
};
},
props: {
tabList: Array
},
watch: {
$route() {
this.initActiveIndex(this.$route.path);
}
},
methods: {
//初始化当前标签样式,防止刷新页面导致标签样式失效
initActiveIndex(currentRouter) {
for (let i = 0; i < this.tabList.length; i++) {
if (currentRouter === this.tabList[i].tabRouter) {
this.activeIndex = i;
return false;
}
}
},
//跳转路由并且设置当前活跃的标签
linkRouter(routerPath, index) {
if (routerPath === this.$route.path) {
return false;
}
this.$router.push({ path: routerPath });
this.activeIndex = index;
}
}
};
</script>
<style scoped>
.tab-container {
display: flex;
flex-direction: row;
border-bottom: 2px solid #e4e7ed;
height: 40px;
}
.tab-single {
margin-right: 2rem;
height: 100%;
line-height: 40px;
display: inline-block;
list-style: none;
font-size: 15px;
font-weight: 500;
color: #303133;
white-space: nowrap;
z-index: 1;
cursor:pointer;
}
.tab-single:hover {
color: #409eff;
}
.tab-active {
color: #409eff;
border-bottom: 2px solid #409eff;
}
</style>
使用方式:
<template>
<SelfTab :tab-list="tabList"></SelfTab>
<router-view />
</template>
<script>
import SelfTab from './SelfTab'
export default {
data() {
return {
tabList: [
{ tabName: "个人信息", tabRouter: "/personInfo" },
{ tabName: "我的文章", tabRouter: "/personArticles" }
]
};
},
components: {
SelfTab
}
};
</script>
效果如下,可以自己修改自定义样式