移动端PC端许多业务代码,会要求实现滚动功能
BetterScroll2.0官网
slider.vue
<template>
<div class="slider" ref="rootRef">
<div class="slider-group">
<div
class="slider-page"
v-for="item in sliders"
:key="item.id"
>
<a :href="item.link">
<img :src="item.pic"/>
</a>
</div>
</div>
<div class="dots-wrapper">
<span
class="dot"
v-for="(item, index) in sliders"
:key="item.id"
:class="{'active': currentPageIndex === index}">
</span>
</div>
</div>
</template>
<script>
import { ref } from 'vue'
import useSlider from './use-slider'
export default {
name: 'slider',
props: {
// 父组件传过来的轮播数组数据
sliders: {
type: Array,
default() {
return []
}
}
},
setup() {
const rootRef = ref(null)
const { currentPageIndex } = useSlider(rootRef)
return {
rootRef,
currentPageIndex
}
}
}
</script>
<style lang="scss" scoped>
.slider {
min-height: 1px;
font-size: 0;
touch-action: pan-y;
.slider-group {
position: relative;
overflow: hidden;
white-space: nowrap;
.slider-page {
display: inline-block;
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
a {
display: block;
width: 100%;
}
img {
display: block;
width: 100%;
}
}
}
.dots-wrapper {
position: absolute;
left: 50%;
bottom: 12px;
line-height: 12px;
transform: translateX(-50%);
.dot {
display: inline-block;
margin: 0 4px;
width: 8px;
height: 8px;
border-radius: 50%;
background: $color-text-l;
&.active {
width: 20px;
border-radius: 5px;
background: $color-text-ll;
}
}
}
}
</style>
useSlider.js
import BScroll from '@better-scroll/core'
import Slide from '@better-scroll/slide'
import { onMounted, onUnmounted, onActivated, onDeactivated, ref } from 'vue'
BScroll.use(Slide)
export default function useSlider(wrapperRef) {
const slider = ref(null)
const currentPageIndex = ref(0)
onMounted(() => {
// 创建betterscroll对象
const sliderVal = slider.value = new BScroll(wrapperRef.value, {
click: true,
scrollX: true,
scrollY: false,
momentum: false,
bounce: false,
probeType: 2,
slide: true
})
// 触发时机:当 slide 切换 page 之后触发
sliderVal.on('slideWillChange', (page) => {
currentPageIndex.value = page.pageX
})
})
onUnmounted(() => {
slider.value.destroy()
})
onActivated(() => {
slider.value.enable()
slider.value.refresh()
})
onDeactivated(() => {
slider.value.disable()
})
return {
slider,
currentPageIndex
}
}
使用:
<div class="slider-wrapper">
<div class="slider-content">
<slider v-if="sliders.length" :sliders="sliders"></slider>
</div>
</div>
导入注册,sliders是轮播数据
import Scroll from '@/components/wrap-scroll'
.slider-wrapper {
position: relative;
width: 100%;
height: 0;
padding-top: 40%;
overflow: hidden;
.slider-content {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
}