核心思想:
slider.vue源码
<template>
<div class="wrapper" ref="wrapper">
<div class="content" ref="content">
<slot></slot>
</div>
</div>
</template>
<script>
import Bscroll from 'better-scroll'
import {
addClass
} from '../common/dom.js'
export default {
props: {
loop: {
type: Boolean,
default: true,
},
autoPlay: {
type: Boolean,
default: true,
},
interval: {
type: Number,
default: 1000
}
},
data() {
return {
scroll: '',
children: []
}
},
components: {},
methods: {
_resetwidth() {
setTimeout(() => {
this._setSliderWidth()
this.init()
}, 20)
},
_setSliderWidth() {
this.children = this.$refs.content.children;
let width = 0;
let sliderWidth = this.$refs.wrapper.clientWidth;
let child = {}
for (let i = 0; i < this.children.length; i++) {
width += sliderWidth;
child = this.children[i]
child.style.width = sliderWidth + 'px'
console.log(child.style.width)
this.children[i].style.width = sliderWidth
addClass(child, 'lunboitem')
}
if (this.loop) {
width += 2 * sliderWidth;
}
this.$refs.content.style.width = width + 'px';
},
init() {
this.scroll = new Bscroll(this.$refs.wrapper, {
scrollX: true,
scrollY: false,
momentum: false, //关闭或者打开惯性运动的执行
snap: true, //隔断(翻页)
snapLoop: this.loop, //无限滚动
snapThreshold: 0,
snapSpeed: 400, //滑动的时间
})
},
},
mounted() {
setTimeout(() => {
this._setSliderWidth()
this.init()
}, 20)
window.addEventListener('resize',()=>{
this._resetwidth()
})
},
created() {},
watch: {}
}
</script>
<style scoped lang="scss">
.wrapper {
overflow: hidden;
.content {
overflow: hidden;
.lunboitem {
float: left;
}
}
}
</style>
dom.js源码
export function addClass(el,classname){
if(hasClass(el,classname)){
return
}
else{
let newClass = el.className.split(' ')
newClass.push(classname)
}
}
export function hasClass(el,classname){
let reg = new RegExp('(^|\\s)'+classname+'($|\\s)')
return reg.test(el.className)
}
使用代码
import Slider from './components/Slider.vue'
components:{
Slider
}
<Slider>
<div class="silderitem" v-for="(item,index) in color" :key='index' :class="item"></div>
</Slider>