better-scroll 实现选项卡和内容的双向滑动(效果展示)
npm i better-scroll --save
<template>
<div class="wrapper">
<div class="menu-wrapper">
<ul>
<li :class="{'actived':actived == index}" v-for="(item,index) in menu" :key="index" @click="checkMenu(index)">
{{item}}
</li>
</ul>
</div>
<div class="item-wrapper" ref="itemWrapper">
<ul>
<li v-for="(item,index) in imgSource" :key="index">
<img :src="item" @load="loadImage" alt="">
</li>
</ul>
</div>
</div>
</template>```
<script>
import BScroll from 'better-scroll'
export default {
data(){
return{
menuWrapper:'',
menu:[
'menu1',
"menu2",
'menu3',
'menu4',
"menu5"
],//选项卡集合
imgSource:[
'https://dummyimage.com/600x800/fef0d1',
"https://dummyimage.com/600x1000/688147",
'https://dummyimage.com/600x600/ecac5f',
'https://dummyimage.com/600x700/87d74f',
"https://dummyimage.com/600x500/4b79bb"
],//图片资源
onload:0,//图片加载完成个数
actived:0,//当前所在的选项卡
listHeight:[]
}
},
mounted(){
},
methods:{
loadImage(){
this.onload ++//加载完成一个图片即onload ++
},
initScorll(){
this.$nextTick(() => {
this.itemScroll = new BScroll(this.$refs.itemWrapper, {
probeType: 3,//允许实时监听 scroll
scrollY: true,//允许竖屏滑动
click: true,
useTransition:false, // 防止iphone微信滑动卡顿
bounce:true
})
this.itemScroll.on('scroll', pos => {
let scrollY = Math.abs(Math.floor(pos.y))
//当滚动距离大于或者等于数组中的某元素 就定位到该选项卡
this.listHeight.forEach((item,index) =>{
if(scrollY >= item){
this.actived = index
}
})
})
})
},
//得到所有选项卡距离顶部的距离数组
getHeight() {
let itemList = this.$refs.itemWrapper.children[0].children
let height = 0
this.listHeight.push(height);
for (let i = 0; i < itemList.length; i++) {
let item = itemList[i];
height += item.clientHeight;
this.listHeight.push(height)
}
},
//选中某一个选项卡同时滚动到对应的区域
checkMenu(ind){
this.actived = ind
let itemList = this.$refs.itemWrapper.children[0].children
this.itemScroll.scrollToElement(itemList[ind],300)
},
},
watch:{
//等待图片加载完以后在初始化BScroll,避免无法滚动
onload(newval,oldval){
if(newval == 5){
this.initScorll()
this.getHeight()
}
}
}
}
</script>
<style lang="less">
html, body, #app {
width: 100%;
height: 100%;
overflow: hidden;
}
.wrapper{
width: 100%;
height: 100%;
overflow: hidden;
display: flex;
flex-direction: row;
}
.actived{
background: #ffffff!important;
}
.menu-wrapper ul li{
list-style: none;
width: 2rem;
height: 0.8rem;
text-align: center;
line-height: 0.8rem;
font-size: .36rem;
background: #f5f5f5;
color: #666666;
}
.item-wrapper ul li{
list-style: none;
}
.item-wrapper ul li img{
width: 100%;
}
</style>