Vue组件封装 - Tab标签滑动切换
VUE+TS
效果
第二版 简单封装Tab标签滑动切换组件,即贴即用,后续会继续改进。
-
<template>
-
<div class="tab-container" v-if="tabList">
-
<div
-
class="tab-title"
-
@click="changeTab(index, $event)"
-
v-for="(item, index) in tabList"
-
:class="[index === statusIndex ? 'active' : '']"
-
:key="index"
-
>
-
{{ item }}
-
</div>
-
<div ref="tabLine" class="tab-line"></div>
-
</div>
-
</template>
-
<script lang="ts">
-
import { Component, Prop, Vue, Ref, Emit } from "vue-property-decorator";
-
@Component
-
export default class Tab extends Vue {
-
@Ref() tabLine: any;
-
@Prop() tabList!: Array<string>;
-
statusIndex: number = 0; // 选中Tab的index
-
offSet: number = 0; // 当前偏移量
-
changeTab(index: number, e: any) {
-
const titleLength = e.target.offsetWidth;
-
this.offSet = this.offSet + (index - this.statusIndex) * titleLength;
-
this.tabLine.style.transform = `translateX(${this.offSet}px)`;
-
this.tabLine.style.transition = "transform .3s";
-
this.statusIndex = index;
-
this.emitTabChange();
-
}
-
@Emit("change")
-
emitTabChange() {
-
return this.statusIndex;
-
}
-
}
-
</script>
-
<style lang="scss" scoped>
-
.tab-container {
-
padding: 0 20px;
-
position: relative;
-
display: flex;
-
align-items: center;
-
justify-content: space-between;
-
position: relative;
-
.tab-title {
-
width: 100%;
-
text-align: center;
-
line-height: 13px;
-
&.active {
-
color: yellowgreen;
-
font-weight: bold;
-
font-size: 16px;
-
}
-
}
-
.tab-line {
-
position: absolute;
-
width: 16%;
-
height: 2px;
-
bottom: -10px;
-
left: 25px;
-
background-color: yellowgreen;
-
}
-
}
-
</style>
使用:
-
<template>
-
<div>
-
<Tab :tabList="['T1', 'T2', 'T3', 'T4', 'T5']" @change="onTabChange"></Tab>
-
</div>
-
</template>
-
<script lang="ts">
-
import Tab from "./Tab.vue";
-
export default class Page extends Vue {
-
onTabChange(index: number) {
-
console.log(index, "+++++++++++");
-
}
-
}
-
</script>