vue利用better-scroll实现轮播图与页面滚动详解

2020-06-16 05:52:23易采站长站整理

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

<script>
import BScroll from 'better-scroll'

export default {
props: {
probeType: {
type: Number,
default: 1
},
click: {
type: Boolean,
default: true
},
listenScroll: {
type: Boolean,
default: false
},
object: {
type: Object,
default: null
},
data: {
type: Array,
default: null
},
string: {
type: String,
default: ''
},
pullup: {
type: Boolean,
default: false
},
beforeScroll: {
type: Boolean,
default: false
},
refreshDelay: {
type: Number,
default: 20
}
},
mounted() {
setTimeout(() => {
this._initScroll()
}, 20)
},
methods: {
_initScroll() {
if (!this.$refs.wrapper) {
return
}
this.scroll = new BScroll(this.$refs.wrapper, {
probeType: this.probeType,
click: this.click
})

if (this.listenScroll) {
let me = this
// pos为位置参数
this.scroll.on('scroll', (pos) => {
me.$emit('scroll', pos)
})
}

if (this.pullup) {
this.scroll.on('scrollEnd', () => {
if (this.scroll.y <= (this.scroll.maxScrollY + 50)) {
this.$emit('scrollToEnd')
}
})
}

if (this.beforeScroll) {
this.scroll.on('beforeScrollStart', () => {
this.$emit('beforeScroll')
})
}
},
disable() {
this.scroll && this.scroll.disable()
},
enable() {
this.scroll && this.scroll.enable()
},
refresh() {
this.scroll && this.scroll.refresh()
},
scrollTo() {
this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments)
},
scrollToElement() {
this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments)
}
},
watch: {
data() {
setTimeout(() => {
this.refresh()
}, this.refreshDelay)
},
string() {
setTimeout(() => {
this.refresh()
}, this.refreshDelay)
},
object() {
setTimeout(() => {
this.refresh()
}, this.refreshDelay)
}
}
}
</script>
<style>
</style>

3.使用封装组件

使用这两个组件的页面组件home.vue 代码如下:


<template>
<div>
<scroll :data="su" class="scroll">
<div>
<div class="slider-wrapper">
<slider>
<div v-for='item in slider'>
<a href="">
<img :src="item.url" alt="">