Vue组件封装 - Tab标签滑动切换

Vue组件封装 - Tab标签滑动切换

Root_030

VUE+TS

效果效果

第二版 简单封装Tab标签滑动切换组件,即贴即用,后续会继续改进。

 
  1. <template>

  2. <div class="tab-container" v-if="tabList">

  3. <div

  4. class="tab-title"

  5. @click="changeTab(index, $event)"

  6. v-for="(item, index) in tabList"

  7. :class="[index === statusIndex ? 'active' : '']"

  8. :key="index"

  9. >

  10. {{ item }}

  11. </div>

  12. <div ref="tabLine" class="tab-line"></div>

  13. </div>

  14. </template>

  15.  
  16. <script lang="ts">

  17. import { Component, Prop, Vue, Ref, Emit } from "vue-property-decorator";

  18.  
  19. @Component

  20. export default class Tab extends Vue {

  21. @Ref() tabLine: any;

  22. @Prop() tabList!: Array<string>;

  23. statusIndex: number = 0; // 选中Tab的index

  24. offSet: number = 0; // 当前偏移量

  25.  
  26. changeTab(index: number, e: any) {

  27. const titleLength = e.target.offsetWidth;

  28. this.offSet = this.offSet + (index - this.statusIndex) * titleLength;

  29. this.tabLine.style.transform = `translateX(${this.offSet}px)`;

  30. this.tabLine.style.transition = "transform .3s";

  31. this.statusIndex = index;

  32. this.emitTabChange();

  33. }

  34.  
  35. @Emit("change")

  36. emitTabChange() {

  37. return this.statusIndex;

  38. }

  39. }

  40. </script>

  41.  
  42. <style lang="scss" scoped>

  43. .tab-container {

  44. padding: 0 20px;

  45. position: relative;

  46. display: flex;

  47. align-items: center;

  48. justify-content: space-between;

  49. position: relative;

  50. .tab-title {

  51. width: 100%;

  52. text-align: center;

  53. line-height: 13px;

  54. &.active {

  55. color: yellowgreen;

  56. font-weight: bold;

  57. font-size: 16px;

  58. }

  59. }

  60. .tab-line {

  61. position: absolute;

  62. width: 16%;

  63. height: 2px;

  64. bottom: -10px;

  65. left: 25px;

  66. background-color: yellowgreen;

  67. }

  68. }

  69. </style>

使用:

 
  1. <template>

  2. <div>

  3. <Tab :tabList="['T1', 'T2', 'T3', 'T4', 'T5']" @change="onTabChange"></Tab>

  4. </div>

  5. </template>

  6. <script lang="ts">

  7. import Tab from "./Tab.vue";

  8. export default class Page extends Vue {

  9. onTabChange(index: number) {

  10. console.log(index, "+++++++++++");

  11. }

  12. }

  13. </script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值