效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b3797aa3c5cc2df9ac13c4e4c61fa110.gif)
子组件WXML
<view class="tabs">
<view class="tab-item"
wx:for="{{tabList}}"
wx:key="index"
data-index="{{index}}"
data-value="{{item}}"
bindtap="changeTab">
<text class="tab-text {{currentIndex == index ? 'active' : ''}}">{{item.name}}</text>
</view>
<view class="line" wx:if="{{show}}" style="left:{{left}}px"></view>
</view>
子组件JS
Component({
data: {
currentIndex: 0,
left: '',
show: false
},
properties: {
tabList: {
type: Array,
value: []
}
},
observers: {
'tabList'(val) {
if (val && val.length) {
this.changeline()
}
}
},
methods: {
changeTab(e) {
let index = e.currentTarget.dataset.index
let value = e.currentTarget.dataset.value
this.setData({
currentIndex: e.currentTarget.dataset.index
})
this.triggerEvent("getCurrentValue", value)
this.changeline()
},
changeline() {
let _this = this
let query = wx.createSelectorQuery().in(this)
query.select(".active").boundingClientRect()
query.exec(function (res) {
_this.setData({
left: res && res[0].left + res[0].width / 2 - 10,
show: true
})
})
}
}
})
子组件JSON
{
"component": true,
"usingComponents": {}
}
子组件WXSS
.tabs {
display: flex;
flex-direction: row;
width: 100%;
height: 80rpx;
justify-content: space-around;
position: relative;
background-color: #fff;
overflow-x: auto;
white-space: nowrap;
}
.tab-text {
font-size: 28rpx;
line-height: 70rpx;
font-weight: 400;
text-align: center;
}
.line {
background: #ffaa7f;
border-radius: 4rpx;
height: 8rpx;
width: 40rpx;
position: absolute;
bottom: 4rpx;
transition: all 0.3s linear;
}
.active {
color: #ffaa7f;
border-color: #ffaa7f;
}
父组件WXML
<view class="container">
<view class="switch-tab">
<tabs tabList="{{tabList}}" bind:getCurrentValue="handleSwitch"></tabs>
</view>
</view>
父组件JS
const app = getApp()
Page({
data: {
tabList: [
{ name: '正在热映', type: 1 },
{ name: '即将上映', type: 0 }
]
},
onLoad: function (options) {
},
onShow: function () {
},
handleSwitch(e) {
console.log(e)
},
})
父组件JSON
{
"navigationBarTitleText": "电影",
"usingComponents": {
"tabs": "../../components/tabs/index"
}
}
父组件WXSS
page {
background: #f2f2f2;
}
.container {
width: 100%;
}
.switch-tab {
width: 100%;
background: #fff;
box-shadow: 0rpx 9rpx 9rpx 0rpx rgba(194, 190, 190, 0.5);
position: fixed;
top: 0;
left: 0;
z-index: 1000;
}