基於vue2.0以及better-scroll實現scroll滑動元件及所實現元件的應用例子
阿新 • • 發佈:2019-02-15
直接上原始碼:
元件:scroll.vue,需要先npm install better-scroll
<template> <div ref="wrapper"> <slot></slot> </div> </template> <script type="text/ecmascript-6"> import BScroll from 'better-scroll' const DIRECTION_H = 'horizontal' const DIRECTION_V = 'vertical' export default { props: { probeType: { type: Number, default: 1 }, click: { type: Boolean, default: false }, listenScroll: { type: Boolean, default: false }, data: { type: Array, default: null }, pullup: { type: Boolean, default: false }, beforeScroll: { type: Boolean, default: false }, refreshDelay: { type: Number, default: 20 }, direction: { type: String, default: DIRECTION_V } }, 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, eventPassthrough: this.direction === DIRECTION_V ? DIRECTION_H : DIRECTION_V }) if (this.listenScroll) { this.scroll.on('scroll', (pos) => { this.$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) } } } </script> <style scoped lang="stylus" rel="stylesheet/stylus"> </style>
應用方法:
引入並註冊元件:
import Scroll from 'base/scroll/scroll'
export default {
components: {
Scroll
}
}
template結構以及style:
效果:圖中輪播圖+列表為滾動區域(recommend-content),即需要滾動的內容;對應的class:slider為輪播圖,recommend-list為列表。由於輪播圖資料以及list資料為動態獲取,實際使用請填充你的資料,以上只給出關鍵結構。
已實現滾動: