<template>
<div class=
"slider-apply"
ref=
"slider"
> <!-- 显示层 -->
<div class=
"slider-group"
ref=
"group"
> <!-- 所有图片包裹层 -->
<slot></slot> <!-- 插槽显示图片内容 -->
</div>
<div class=
"dots"
> <!-- 提示圆点 -->
<div class=
"dot"
v-
for
=
"(item, index) in dots"
:key=
"index"
:class=
"currentIndex===index?'active':''"
></div>
</div>
</div>
</template>
<script type=
'text/ecmascript-6'
>
import BScroll from
'better-scroll'
export
default
{
data () {
return
{
dots: [],
currentIndex: 0
}
},
props: {
isLoop: {
type: Boolean,
default
:
true
},
isAutoPlay: {
type: Boolean,
default
:
true
},
interval: {
type: Number,
default
: 2000
}
},
mounted () {
setTimeout(() => {
this
.setSliderWidth()
this
.initDots()
this
.initSlider()
if
(
this
.isAutoPlay) {
this
.autoPlay()
}
}, 20)
},
methods: {
setSliderWidth () {
const clientWidth =
this
.$refs.slider.clientWidth
let sliderWidth = 0
this
.children =
this
.$refs.group.children
for
(let i = 0; i <
this
.children.length; i++) {
this
.children[i].style.width = clientWidth +
'px'
sliderWidth += clientWidth
}
if
(
this
.isLoop) {
sliderWidth += clientWidth * 2
}
this
.$refs.group.style.width = sliderWidth +
'px'
},
initDots () {
this
.dots =
new
Array(
this
.children.length)
},
initSlider () {
this
.slider =
new
BScroll(
this
.$refs.slider, {
scrollX:
true
,
scrollY:
false
,
snap: {
loop:
this
.isLoop,
threshold: 0.3,
speed: 400
}
})
this
.slider.on(
'scrollEnd'
, () => {
const pageIndex =
this
.slider.getCurrentPage().pageX
this
.currentIndex = pageIndex
if
(
this
.isAutoPlay) {
clearTimeout(
this
.timer)
this
.autoPlay()
}
})
},
autoPlay () {
this
.timer = setTimeout(() => {
this
.slider.next(400)
},
this
.interval)
}
},
destroyed () {
clearTimeout(
this
.timer)
}
}
</script>
<style lang=
"stylus"
scoped>
.slider-apply
position relative
height 200px
width 100%
overflow hidden
border-radius 5px
.dots
position absolute
bottom 10px
left 50%
transform translate(-50%, 0)
display flex
.dot
margin 0 10px
height 7px
width 7px
background
#fff
border-radius 50%
.active
width 15px
border-radius 50% 5px
</style>