18910140161

better-scroll快速上手及封装(vue项目)

顺晟科技

2022-09-13 11:28:48

246

better-scroll快速上手及封装(vue项目) BetterScroll 是一款重点解决移动端(已支持 PC)各种滚动场景需求的插件。它的核心是借鉴的iscroll的实现,它的 API 设计基本兼容 iscroll,在 iscroll 的基础上又扩展了一些 feature 以及做了一些性能优化。 BetterScroll 是使用纯 JavaScript 实现的,这意味着它是无依赖的。

愿你有诗有梦,有坦荡荡的远方

本文声明:这是一篇学习coderwhy老师的vue2课程的一个笔记,所以本文章是在vue项目中实现,没学过vue的大佬们可以举一反三。

使用场景及介绍

BetterScroll 是一款重点解决移动端(已支持 PC)各种滚动场景需求的插件。它的核心是借鉴的iscroll的实现,它的 API 设计基本兼容 iscroll,在 iscroll 的基础上又扩展了一些 feature 以及做了一些性能优化。
BetterScroll 是使用纯 JavaScript 实现的,这意味着它是无依赖的。

安装

npm install @better-scroll/core --save

基本使用

<div class="wrapper" ref="wrapper">
<ul class="scroll-content">
...
</ul>
</div>
data() {
return {
scroll: null,
};
},
mounted() {//不用created,因为那时候还没将元素放上去
this.scroll = new betterScroll(this.$refs.wrapper,{
// ...... 详见配置项
});
},
...

 

 

 

常见配置项

1. click

  • 类型:boolean
  • 默认值:false
  • 作用:BetterScroll 默认会阻止浏览器的原生 click 事件。当设置为 true,BetterScroll 会派发一个 click 事件,我们会给派发的 event 参数加一个私有属性 `_constructed`,值为 true。

2. probeType

  • 类型:number
  • 默认值:0
  • 可选值:1|2|3
  • 作用:决定是否派发 scroll 事件,对页面的性能有影响,尤其是在 `useTransition` 为 true 的模式下。

 

// 派发 scroll 的场景分为两种:
// 1. 手指作用在滚动区域(content DOM)上;
// 2. 调用 scrollTo 方法或者触发 momentum 滚动动画(其实底层还是调用 scrollTo 方法)

// 对于 v2.1.0 版本,对 probeType 做了一次统一

// 1. probeType 为 0,在任何时候都不派发 scroll 事件,
// 2. probeType 为 1,仅仅当手指按在滚动区域上,每隔 momentumLimitTime 毫秒派发一次 scroll 事件,
// 3. probeType 为 2,仅仅当手指按在滚动区域上,一直派发 scroll 事件,
// 4. probeType 为 3,任何时候都派发 scroll 事件,包括调用 scrollTo 或者触发 momentum 滚动动画

3. pullUpLoad

  • 类型:Boolean | Object
  • 默认值:false
  • 作用:这个配置用于做上拉加载功能,默认为 false。当设置为 true 或者是一个 Object 的时候,可以开启上拉加载,例如:

 

pullUpLoad:true,//相当于pullUpLoad:{ threshold:0 }

可以配置离(`threshold`)来决定开始加载的时机。

封装成一个独立组件

<template>
<div ref="wrapper" class="wrapper">
<div>
<slot></slot>
</div>
</div>
</template>

<script>
import BScroll from "better-scroll";
export default {
name: "BetterScroll",
data() {
return {
bs: null,
};
},
props: {
probeType: {
type: Number,
default: 0,
},
pullUpLoad: {
type: Boolean,
default: false,
},
},
mounted() {
setTimeout(() => {
this.bs = new BScroll(this.$refs.wrapper, {
probeType: this.probeType,
click: true,
pullUpLoad: this.pullUpLoad,
});
this.bs.on("scroll", (option) => {
this.$emit("scroll", option);
});
this.bs.on("pullingUp", () => {
this.$emit("pullingUp");
setTimeout(() => {
this.bs.finishPullUp();
}, 2000);
});
}, 1000);
},
methods: {
scrollTo(x, y, time = 500) {
this.bs&&this.bs.scrollTo(x, y, time);
},
refresh(){
this.bs&&this.bs.refresh();
}
},
};
</script>

<style scoped>
.wrapper {
overflow: hidden;
}
</style>

使用组件

import betterScroll from "better-scroll";
<better-scroll
:probeType="3"
:pullUpLoad="true"
@scroll="contentScroll"
@pullingUp="contentPullingUp"
>

做世界的水手,奔赴所有的港口

相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航