持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第30天,点击查看活动详情
前面我们使用 CSS 和 React实现了,接下来是使用 Vue实现。这次我们把目光放到了移动端上面。
基础的使用方法
<div v-if="recommends.length" class="slider-wrapper">
<slider>
<div v-for="item in recommends">
<a :href="item.linkUrl">
<img :src="item.picUrl">
</a>
</div>
</slider>
</div>
大概就是这个样子
大致可以看出我们的结构被分成了上下部分。
<template>
<div class="slider" ref="slider">
<div class="slider-group" ref="sliderGroup">
<slot>
</slot>
</div>
<div class="dots">
<span class="dot" v-for="(item, index) in dots" :key="index"
:class="{ active: currentPageIndex === index }"></span>
</div>
</div>
</template>
dots 是下方的小圆点。这个是动态变化的,也就是说我们其实并不知道,数量是根据上面图片的数量生成的。
这样看来,大概就可以写出小圆点的代码了。
data() {
return {
dots: [],
currentPageIndex: 0
}
},
mounted() {
setTimeout(() => {
this._initDots();
}, 20);
},
methods: {
_initDots() {
this.dots = new Array(this.children.length)
},
}
接下来需要计算整个轮播图的长度,并为轮播图的每一个图片设置宽度。
mounted() {
setTimeout(() => {
this._setSliderWidth();
}, 20)
},
使用 refs 获取 slot 中的内容,为每一个 child 添加 class,同时获取其高度,将其添加到父元素上。
_setSliderWidth() {
this.children = this.$refs.sliderGroup.children
let width = 0
let sliderWidth = this.$refs.slider.clientWidth
for (let i = 0; i < this.children.length; i++) {
let child = this.children[i]
addClass(child, 'slider-item')
child.style.width = sliderWidth + 'px'
width += sliderWidth
}
this.$refs.sliderGroup.style.width = width + 'px'
},
这里判断元素上面是否存在类名,我们可以通过正则,进行判断。
addClass(el, className) {
if (this.hasClass(el, className)) {
return
}
let newClass = el.className.split(' ')
newClass.push(className)
el.className = newClass.join(' ')
},
hasClass(el, className) {
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
return reg.test(el.className)
},
实现轮播效果
这里可以借助 better-scroll 更加完美地实现
BetterScroll 是一款重点解决移动端(已支持 PC)各种滚动场景需求的插件。它的核心是借鉴的 iscroll 的实现,它的 API 设计基本兼容 iscroll,在 iscroll 的基础上又扩展了一些 feature 以及做了一些性能优化。BetterScroll 是使用纯 JavaScript 实现的
_initSlider() {
this.slider = new BScroll(this.$refs.slider, {
scrollX: true,
scrollY: false,
momentum: false,
snap: true,
snapLoop: this.loop,
snapThreshold: 0.3,
snapSpeed: 400
})
this.slider.on('scrollEnd', () => {
let pageIndex = this.slider.getCurrentPage().pageX
if (this.loop) {
pageIndex -= 1
}
this.currentPageIndex = pageIndex
if (this.autoPlay) {
this._play()
}
})
this.slider.on('beforeScrollStart', () => {
if (this.autoPlay) {
clearTimeout(this.timer)
}
})
},
跳转使用的是 goToPage 方法。
_play() {
let pageIndex = this.currentPageIndex + 1
if (this.loop) {
pageIndex += 1
}
this.timer = setTimeout(() => {
this.slider.goToPage(pageIndex, 0, 400)
}, this.interval)
}
当页面卸载的时候,清除定时器。
beforeDestroy() {
clearTimeout(this.timer)
},
文章的最后放出完整的代码
<template>
<div class="slider" ref="slider">
<div class="slider-group" ref="sliderGroup">
<slot>
</slot>
</div>
<div class="dots">
<span class="dot" :class="{ active: currentPageIndex === index }" v-for="(item, index) in dots"></span>
</div>
</div>
</template>
<script type="text/ecmascript-6">
import BScroll from 'better-scroll'
export default {
name: 'slider',
props: {
loop: {
type: Boolean,
default: true
},
autoPlay: {
type: Boolean,
default: true
},
interval: {
type: Number,
default: 4000
}
},
data() {
return {
dots: [],
currentPageIndex: 0
}
},
mounted() {
setTimeout(() => {
this._setSliderWidth()
this._initDots()
this._initSlider()
if (this.autoPlay) {
this._play()
}
}, 20)
window.addEventListener('resize', () => {
if (!this.slider) {
return
}
this._setSliderWidth(true)
this.slider.refresh()
})
},
activated() {
if (this.autoPlay) {
this._play()
}
},
deactivated() {
clearTimeout(this.timer)
},
beforeDestroy() {
clearTimeout(this.timer)
},
methods: {
addClass(el, className) {
if (this.hasClass(el, className)) {
return
}
let newClass = el.className.split(' ')
newClass.push(className)
el.className = newClass.join(' ')
},
hasClass(el, className) {
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
return reg.test(el.className)
},
_setSliderWidth(isResize) {
this.children = this.$refs.sliderGroup.children
let width = 0
let sliderWidth = this.$refs.slider.clientWidth
for (let i = 0; i < this.children.length; i++) {
let child = this.children[i]
this.addClass(child, 'slider-item')
child.style.width = sliderWidth + 'px'
width += sliderWidth
}
if (this.loop && !isResize) {
width += 2 * sliderWidth
}
this.$refs.sliderGroup.style.width = width + 'px'
},
_initSlider() {
this.slider = new BScroll(this.$refs.slider, {
scrollX: true,
scrollY: false,
momentum: false,
snap: true,
snapLoop: this.loop,
snapThreshold: 0.3,
snapSpeed: 400
})
this.slider.on('scrollEnd', () => {
let pageIndex = this.slider.getCurrentPage().pageX
if (this.loop) {
pageIndex -= 1
}
this.currentPageIndex = pageIndex
if (this.autoPlay) {
this._play()
}
})
this.slider.on('beforeScrollStart', () => {
if (this.autoPlay) {
clearTimeout(this.timer)
}
})
},
_initDots() {
this.dots = new Array(this.children.length)
},
_play() {
let pageIndex = this.currentPageIndex + 1
if (this.loop) {
pageIndex += 1
}
this.timer = setTimeout(() => {
this.slider.goToPage(pageIndex, 0, 400)
}, this.interval)
}
}
}
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
.slider
min-height: 1px
.slider-group
position: relative
overflow: hidden
white-space: nowrap
.slider-item
float: left
box-sizing: border-box
overflow: hidden
text-align: center
a
display: block
width: 100%
overflow: hidden
text-decoration: none
img
display: block
width: 100%
.dots
position: absolute
right: 0
left: 0
bottom: 12px
text-align: center
font-size: 0
.dot
display: inline-block
margin: 0 4px
width: 8px
height: 8px
border-radius: 50%
background: rgba(255, 255, 255, 0.5)
&.active
width: 20px
border-radius: 5px
background: rgba(255, 255, 255, 0.8)
</style>