微信小程序点击tab栏切换,点击某个tab滚动到中间( uniapp )
之前写过原生js的tab栏滚动到中间,正好最近有个uniapp小程序项目中要用到tab切换滚动, 写个demo发出来
+ 注意
- 如果tab数据是服务端请求的,需要等到接口请求后再去调用initScrollData方法获取元素信息;
- 如果一进来需要默认展示tab不是第一个, 需要设置tabIndex,需要等initScrollData执行完毕后再去调用scrollDom方法
<template>
<view class="container">
<view class="scroll">
<view class="scroll-con">
<scroll-view scroll-x scroll-with-animation :throttle="false" :scroll-left="scrollToLeft">
<view class="scroll-area">
<block v-for="(item, index) in tabs" :key="index">
<view :class="['scroll-item', { 'scroll-activer': index == tabIndex }]" @tap="handleBusChange(index)">
{{item}}
<view class="scroll-border" v-if="index == tabIndex"></view>
</view>
</block>
</view>
</scroll-view>
</view>
</view>
</view>
</template>
<script>
import mixins from '@/mixins/index.js';
export default {
mixins: [mixins],
components: {
},
data: () => ({
tabs:['中国','美国','加拿大','印度','巴基斯坦','法国','德国','澳大利亚','泰国','巴西'],
scrollAreaLeft:0,
scrollAreaWidth:0,
tabItemList:[],
scrollToLeft: 0,
tabIndex:0,
}),
computed: {},
// 页面周期函数--监听页面加载
onLoad(options) {
this.initScrollData()
},
onPullDownRefresh() {
},
onReachBottom() {
},
methods: {
handleBusChange(index) {
this.tabIndex = index;
this.scrollDom(index);
},
initScrollData(){
const query = uni.createSelectorQuery().in(this);
query.select('.scroll-area').fields({
rect: true,
size: true
}, res => {
this.scrollAreaLeft = res.left;
this.scrollAreaWidth = res.width;
});
query.selectAll('.scroll-item').fields({
rect: true,
size: true
}, data => {
data.forEach((item, index) => {
this.tabItemList.push({
width: item.width,
left: item.left
});
});
});
query.exec();
},
scrollDom(index) {
const offsetLeft = this.tabItemList[index].left - this.scrollAreaLeft
const scrollLeft = offsetLeft - (this.scrollAreaWidth - this.tabItemList[index].width) / 2;
this.scrollToLeft = scrollLeft < 0 ? 0 : scrollLeft;
}
}
};
</script>
<style lang="scss">
.container {
.scroll {
margin-top: 16rpx;
.scroll-con {
overflow-x: auto;
white-space: nowrap;
background: #fff;
.scroll-item {
position: relative;
display: inline-block;
text-align: center;
padding: 28rpx 0;
margin-right: 36rpx;
font-size: 32rpx;
font-weight: bold;
&:first-child {
margin-left: 24rpx;
}
&:last-child {
margin-right: 24rpx;
}
.scroll-border {
position: absolute;
bottom: 0rpx;
left: 0;
right: 0;
margin: auto;
width: 66rpx;
height: 6rpx;
background: #ff5548;
border-radius: 2rpx;
}
}
.scroll-activer {
color: #ff5548;
}
}
}
}
</style>