本文来源于 better-scroll在vue3里的基本使用_想爬树的青年猪的博客-CSDN博客
<template>
<div class="wapper">
<div class="content">
<!-- 纵向滚动盒子 -->
<div class="box" v-for="(i,index) in 6">纵向滚动盒子{{index}}</div>
<!-- 横向滚动盒子 -->
<div class="wapper2">
<div class="content2">
<div class="item" v-for="(item,index) in 6">横向滚动盒子{{index}}</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { onMounted, ref, nextTick } from 'vue'
import BScroll from 'better-scroll'
export default {
setup(){
onMounted(async ()=>{
await nextTick()
// 实例和配置
BS.value = new BScroll('.wapper',{
scrollY: true, //纵向滚动
mouseWheel: true, //可以用鼠标滚轮滚动
probeType: 3, //开启滚动事件
click: true, //点击事件,默认false
pullUpLoad: { //开启上拉加载
threshold: -10 //设置上拉事件触发的距离
},
pullDownRefresh: { //开启下拉刷新
stop: 30, //刷新时离顶部停留的距离
threshold: 40 //设置下拉事件触发的距离
}
})
// 监听滚动距离
BS.value.on('scroll',(position)=>{
console.log(position.x) //打印x轴距离,是负数
console.log(position.y) //打印y轴距离,是负数
// Math.abs(position.y) 改为正数
})
// 上拉加载
BS.value.on('pullingUp',()=>{
console.log('上拉加载更多')
BS.value.finishPullUp() //完成上拉加载事件,不写下次再拉就没反应了
})
//下拉刷新
BS.value.on('pullingDown',()=>{
console.log('上拉加载更多')
BS.value.finishPullDown() //完成下拉刷新事件,不写下次再拉就没反应了
})
BS.value.refresh() //重新计算滚动盒子的宽高
// 横向滚动实例与配置,一般要以下两项配置就可以了
BS2.value = new BScroll('.wapper2',{
scrollX: true,
eventPassthrough: "vertical",
})
BS2.value.refresh()
})
const BS = ref(null)
const BS2 = ref(null)
}
}
</script>
<style lang="less" scoped>
.wapper{
width: 100%;
height: 500px;
overflow: hidden;
background-color: royalblue;
.content{
width: 100%;
.box{
margin: 10px;
height: 100px;
border-radius: 10px;
line-height: 100px;
text-align: center;
background-color: #fff;
}
.wapper2{
width: 100%;
overflow: hidden;
.content2{
display: flex;
justify-content: space-evenly;
width: 600px;
.item{
width: 80px;
height: 80px;
border-radius: 10px;
font-size: 10px;
line-height: 80px;
text-align: center;
color: #fff;
background-color: #663399;
}
}
}
}
}
</style>>