官方文档:[https://cnpmjs.org/package/vue2-better-scroll]
下载
1.yarn add vue2-better-scroll
2.npm install vue2-better-scroll -s
使用
直接上代码
<template>
<div id="app">
<div class="he">这是一个刷新demo</div>
<main class="position-box">
<!-- 需要一个创建一个父容器 组件高度默认等于父容器的高度 -->
<vue-better-scroll
class="wrapper"
ref="scroll"
:scrollbar="scrollbarObj"
:pullDownRefresh="pullDownRefreshObj"
:pullUpLoad="pullUpLoadObj"
:startY="parseInt(startY)"
@pulling-down="onPullingDown"
@pulling-up="onPullingUp"
>
<ul class="list-content">
<li class="list-item" v-for="item in items" :key="item.id">
{{ item }}
</li>
</ul>
</vue-better-scroll>
</main>
<button class="go-top" @click="scrollTo">返回顶部</button>
</div>
</template>
<script>
import VueBetterScroll from "vue2-better-scroll";
// import VueBetterScroll from './lib'
let count = 1;
export default {
name: "app",
components: { VueBetterScroll },
data() {
return {
// 这个配置可以开启滚动条,默认为 false。当设置为 true 或者是一个 Object 的时候,都会开启滚动条,默认是会 fade 的
scrollbarObj: {
fade: true,
},
// 这个配置用于做下拉刷新功能,默认为 false。当设置为 true 或者是一个 Object 的时候,可以开启下拉刷新,可以配置顶部下拉的距离(threshold) 来决定刷新时机以及回弹停留的距离(stop)
pullDownRefreshObj: {
threshold: 90,
stop: 40,
},
// pullDownRefreshObj: false,
// 这个配置用于做上拉加载功能,默认为 false。当设置为 true 或者是一个 Object 的时候,可以开启上拉加载,可以配置离底部距离阈值(threshold)来决定开始加载的时机
pullUpLoadObj: {
threshold: 0,
txt: {
more: "加载更多",
noMore: "没有更多数据了",
},
},
startY: 0, // 纵轴方向初始化位置
scrollToX: 0,
scrollToY: 0,
scrollToTime: 500,
items: [],
};
},
mounted() {
this.onPullingDown();
},
methods: {
// 滚动到页面顶部
scrollTo() {
this.$refs.scroll.scrollTo(
this.scrollToX,
this.scrollToY,
this.scrollToTime
);
},
// 模拟数据请求
getData() {
return new Promise((resolve) => {
setTimeout(() => {
const arr = [];
for (let i = 0; i < 10; i++) {
arr.push(count++);
}
resolve(arr);
}, 1000);
});
},
onPullingDown() {
// 模拟下拉刷新
console.log("下拉刷新");
count = 0;
this.getData().then((res) => {
this.items = res;
this.$refs.scroll.forceUpdate(true);
});
},
onPullingUp() {
// 模拟上拉 加载更多数据
console.log("上拉加载");
this.getData().then((res) => {
this.items = this.items.concat(res);
if (count < 50) {
this.$refs.scroll.forceUpdate(true);
} else {
this.$refs.scroll.forceUpdate(false);
}
});
},
},
};
</script>
<style>
.position-box {
position: fixed;
top: 40px;
left: 0;
right: 0;
bottom: 0;
}
.he {
background: #ff6700;
width: 100%;
position: relative;
z-index: 1000;
}
.he {
padding: 0;
margin: 0;
text-align: center;
}
.go-top {
position: fixed;
right: 0;
bottom: 10px;
}
.list-content {
list-style-type: none;
width: 100%;
padding: 0;
}
.list-item {
background: chocolate;
margin-top: 10px;
width: 100%;
height: 60px;
text-align: center;
}
</style>