template部分
<template>
<view class="o-content">
<!-- 菜单 -->
<view class="tabMenu">
<scroll-view class="scroll-view" scroll-x="true">
<view class="tab-list" :class="tabIndex == index ? 'actived' : '' " v-for="(item,index) in tablist" :key="index" @click="tabClick(index)">
{{item}}
</view>
</scroll-view>
</view>
<view class="tab-content">
<swiper class="swiper-box" :interval="3000" :duration="1000" :current='tabIndex' :style="{height:swiperheight+'px'}" @change="tabChange">
<swiper-item v-for="(item,index) in listContent" :key="index">
{{item.name}}
</swiper-item>
</swiper>
</view>
</view>
</template>
js部分
<script>
export default {
data() {
return {
tabIndex:0,
tablist:[1,2,3,4],
listContent:[
{id:1,name:'第一个页面'},
{id:2,name:'第二个页面'},
{id:3,name:'第三个页面'},
{id:4,name:'第四个页面'},
],
swiperheight:400
}
},
methods: {
tabClick(index){
this.tabIndex=index
},
tabChange(e){
console.log(e);
var index = e.detail.current;
this.tabIndex = index;
}
}
}
</script>
css部分
<style>
.tabMenu{
width: 100%;
display: flex;
flex-wrap: nowrap;
white-space: nowrap;
}
.tab-list{
display: inline-block;
padding: 20rpx;
text-align: center;
box-sizing: border-box;
}
.actived{
color: #3A6EFA;
border-bottom: 2px solid #3A6EFA;
}
</style>
1.首先这个dome是利用了scroll(滚动视图区域)与swiper(滑块视图容器)相关特性来实现选项卡的功能。
2.选中功能的实现:
首先在data里面定义好一个把变量,之后才能利用好这个变量来达到目的。
其次在css样式中定义好一个选中时候的类名,之后好通过逻辑来添加此类名。
然后呢就是使用v-for遍历数据,这里记得要绑定key值
最后(最核心的部分):
使用click或者tap方法写一个函数,使得每次点击都能够将Index值与tabIndex绑定
由于之前index与tapIndex绑定了,所以这里可以动态绑定class利用三元运算符来判断是否选中。:class="tabIndex == index ? 'actived' : ' ' " 每次点击tabIndex相等则赋予选中的class样式,其余的没有点击的导航按钮呢则是不做操作。
3.内容与导航按钮联动效果
这个首先遍历以及相关样式这里不过多介绍,主要讲方法,这里用的是change,起作用是当滑块内容改变时触发的方法。
然后这里的关键属性就是e里面current属性,这里可以动态绑定current就相当于一个桥梁的作用,使得current与tabIndex绑定然后滑块怎么去操作被选中的状态呢,就是通过change方法将index的值赋给tabIndex,当然这里的index是内容遍历后的索引。这样的话就实现了选项卡的功能了。
~~~~~~ (^-^)~~~~~是不是特别简单呀!!!嘿嘿~