什么是tab选项卡
tab选项卡简单来讲就是每一项标题对应一项内容,点击不同标题展示不同内容
如何实现tab切换的效果
a.使用组件
我们给我们的组件传递一个current参数,通过控制current的值,配合v-if和v-show进行内容的显示与隐藏
下面是uni-app分段器的代码
使用组件
current参数 用于切换不同选项卡内容
tabList参数 用于配置tab栏目标题的数组,每一项标题
<common-tab :current=current :tabList="tabList" @clickItem="onClickItem" />
定义两个参数
current:0
tabList:['标题1','标题2','标题3']
onClickItem(e){
this.current = e.currentIndex
}
b.封装组件
本次封装的tab组件底部横条添加了一个位移动画效果,如果不需要自行更改样式 以下是全部代码
<template>
<view class="box">
<view class="container">
<view class="tab-box" v-for="(item, index) in tabList" :style="{ width: `${100 / tabList.length}` + `%` }"
:key="index" @click="check(index)">
<view class="title" :style="{ color: textColor(index) }">{{ item }}
</view>
</view>
</view>
<view class="bar" :style="{ width: `${100 / tabList.length}` + '%', transform: move }">
<view class="line"></view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
currentIndex: 0
}
},
props: {
tabList: {
type: Array,
default() {
return ["已完成", "未完成"]
}
},
current: {
type: Number,
default() {
return 0
}
}
},
computed: {
textColor() {
return (index) => {
if (this.currentIndex == index) {
return '#fe6c3b'
} else {
return '#181818'
}
}
},
move() {
let d = ''
d = this.current * 100 + '%'
return `translate3d(${d},0,0 )`
}
},
methods: {
check(index) {
this.currentIndex = index
this.$emit('clickItem', { currentIndex: index })
}
}
}
</script>
<style lang="less" scoped>
.box {
display: flex;
flex-direction: column;
height: 120rpx;
.container {
display: flex;
justify-content: space-between;
position: relative;
.tab-box {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100rpx;
.title {
color: #181818;
font-size: 30rpx;
}
}
}
.bar {
margin-top: -12rpx;
display: flex;
justify-content: center;
transition: .3s
}
.line {
background-color: #fe6c3b;
width: 148rpx;
height: 7rpx;
border-radius: 12rpx;
}
}
</style>