Vue Tab切换组件简单封装,满足自己简单的功能,可以直接拿去使用!
<template>
<div class="tab-list" ref="tabList">
<div v-for="(item,index) in valueList" :key="index" class="tab-item" @click="itemClick(index)"
:style="{width: tabItemWidth + 'px', color: currentIndex === index ? activeColor : '#333333'}" >
{{item.name}}
</div>
<div class="bottom-line" :style="{width: tabItemWidth / 3 + 'px', left: lineLeft, backgroundColor: activeColor}" ></div>
</div>
</template>
<script>
export default {
props: {
valueList: {
type: Array,
default() { return [] }
},
defalutIndex: {
type: Number,
default: 0
},
needUnderline: {
type: Boolean,
default: true
},
needBorderLine: {
type: Boolean,
default: true
},
background: {
type: String,
default: 'white'
},
activeColor: {
type: String,
default: '#3292FF'
}
},
data() {
return {
tabItemWidth:200,
currentIndex:0
};
},
mounted() {
this.initView()
},
computed: {
lineLeft() {
const lineWidth = this.tabItemWidth / 3
const left = this.currentIndex * this.tabItemWidth + this.tabItemWidth / 2 - lineWidth / 2
return left + 'px'
}
},
methods: {
initView(){
this.currentIndex = this.defalutIndex
this.tabItemWidth = this.$refs.tabList.offsetWidth / this.valueList.length
},
itemClick(index) {
this.currentIndex = index
this.$emit('change', index)
}
},
};
</script>
<style scoped>
.tab-list{background: #fff;}
.tab-list {width: 100%;height: 44px;position: relative;display: flex;justify-content: space-around;
align-items: center;}
.tab-list .tab-item {height: 43px;line-height: 43px;font-size: 15px;font-weight: bold;text-align: center;transition-duration: 0.3s;}
.tab-list .bottom-line {height: 3px;border-radius: 4px;position: absolute;bottom: 0;transition-duration: 0.3s;}
</style>
可以通过keep-alive 保留数据值 填写数据时切换到其他页面,后返回当前页数据保留 ,主要用于保留组件状态或避免重新渲染