封装函数:
function fn(styles, index=0) {
// ES6提供的箭头函数
styles.map((item, key) => {
if (key == index) {
item['class'] = 'color'
} else {
item['class'] = ''
}
})
return{
index,
styles
};
}
module.exports={
fn:fn
}
js引入:
// 引入封装函数
const obj=require("../../utils/function.js");
Page({
/**
* 页面的初始数据
*/
data: {
styles:[
{class:"color",text:'商品参数'},
{class:"",text:'商品介绍'},
{class:"",text:'规格明细'}
],
index:0
},
tab(evt){
// console.log(evt)
// 对应下标
let index=evt.target.dataset.index;
let styles=this.data.styles;
let ret=obj.fn(styles,index);
this.setData(ret);
},
changetab(evt){
// console.log(evt)
// 滑动下面tab对应上面下标
let index=evt.detail.current;
let styles=this.data.styles;
let ret=obj.fn(styles,index);
this.setData(ret);
},
页面:
<view class="box">
<block wx:for="{{styles}}" wx:key="styles">
<view class="{{item.class}}" bindtap="tab" data-index="{{index}}">{{item.text}}</view>
</block>
</view>
<swiper circular="{{true}}" current="{{index}}" bindchange="changetab">
<view class="content">
<swiper-item >
<view >商品参数</view>
</swiper-item>
<swiper-item >
<view>商品介绍</view>
</swiper-item>
<swiper-item >
<view>规格明细</view>
</swiper-item>
</view>
</swiper>
wxss:
.box{
width: 100%;
height: 100rpx;
/* background-color: blueviolet; */
display: flex;
justify-content: space-around;
}
.content{
/* height:200rpx ; */
/* background-color: cadetblue; */
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 200rpx 0;
box-sizing: border-box;
}
.color{
color: red;
}
本文介绍了如何在微信小程序中封装函数实现Tab切换效果。通过使用ES6箭头函数和map方法处理样式,当点击或滑动时更新当前选中项的样式。示例代码包括js函数、页面数据、事件处理和wxss样式设置。

7306

被折叠的 条评论
为什么被折叠?



