仿element-ui tabs支持路由的组件

仿element-ui tabs的路由组件


很喜欢element-ui的这个tab组件,但是这里设计应该是用来做html显示的切换,本来也考虑将组件直接放到这个tab内,切换tab显示不同组件,但是试了一下未激活的标签内容也会预先加载,不太友好。尝试将其改为路由的方式,发现太麻烦了,所以参照这个样式写了个支持路由的组件。

element-ui的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>

效果如下,可以自己修改自定义样式
在这里插入图片描述

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值