npm install @better-scroll/core --save
import BScroll from '@better-scroll/core'
Scroll.vue
<template>
<div ref="rootRef">
<slot></slot>
</div>
</template>
<script>
import useScroll from './use-scroll'
import { ref } from 'vue'
export default {
// eslint-disable-next-line
name: 'scroll',
props: {
click: {
type: Boolean,
default: true
},
probeType: {
type: Number,
default: 0
}
},
emits: ['scroll'],
setup (props, { emit }) {
const rootRef = ref(null)
const scroll = useScroll(rootRef, props, emit)
return {
rootRef,
scroll
}
}
}
</script>
use-scroll.js
import BScroll from '@better-scroll/core'
import ObserveDOM from '@better-scroll/observe-dom'
import { onMounted, onUnmounted, onActivated, onDeactivated, ref } from 'vue'
BScroll.use(ObserveDOM)
export default function useScroll (wrapperRef, options, emit) {
const scroll = ref(null)
onMounted(() => {
const scrollVal = scroll.value = new BScroll(wrapperRef.value, {
observeDOM: true, // 监听数据的变化,dom自动更新, 执行refresh, 内部重新计算
...options
})
if (options.probeType > 0) {
scrollVal.on('scroll', (pos) => {
emit('scroll', pos)
})
}
})
onUnmounted(() => {
scroll.value.destroy()
})
onActivated(() => {
})
onDeactivated(() => {
})
return scroll
}
import { h, mergeProps, withCtx, renderSlot, ref, computed, watch, nextTick } from 'vue'
import Scroll from '@/base/Scroll/Scroll.vue'
import { useStore } from 'vuex'
export default {
name: 'wrap-scroll',
props: Scroll.props,
emits: Scroll.emits,
render (ctx) { // ctx上下文 可以理解为this
return h(Scroll, mergeProps({
ref: 'scrollRef'
}, ctx.$props, {
onScroll: (e) => {
ctx.$emit('scroll', e)
}
}), {
default: withCtx(() => {
return [renderSlot(ctx.$slots, 'default')]
})
})
},
setup() {
const scrollRef = ref(null)
const scroll = computed(() => {
return scrollRef.value.scroll
})
const store = useStore()
const playlist = computed(() => store.state.playlist)
watch(playlist, async () => {
await nextTick()
scroll.value.refresh()
})
return {
scrollRef,
scroll
}
}
}
import Scroll from '@/components/wrap-scroll'
完事