Vue version carousel

yang 2020-11-09 14:29:30
vue version carousel


mySwiper.vue

<template>
<div class="swiper-box" ref="swiperBox">
<!-- Slider body -->
<div class="swiper-wrapper" :style="{width: width + 'rem', height: oHeight}" @touchstart="startMove"
@touchend="endMove" @touchmove="move" ref="sliderBox">
<slot class="swiper-sliber" />
</div>
<!-- Button -->
<div class="btn-box" v-if="nextBtn" @touchstart="startMove" @touchend="endMove" @touchmove="move">
<p @click.stop="handleLast" :class="{'click': isClickL}"><i class="iconfont icon-arrow-left-s-fill"></i></p>
<p @click.stop="handleNext" :class="{'click': isClickR}"><i class="iconfont icon-arrow-right-s-fill"></i>
</p>
</div>
<!-- Pagination text -->
<div v-if="pagingText !== 'none'" class="paging-text-box"
:class="{left: pagingPosition === 'left', right: pagingPosition === 'right'}">
<span class="paging">{{pagingText !== 'none'? pagingText : ''}}{{loop ? length-2 + '/' + index : length + '/' + (index + 1)}}</span>
</div>
<!-- Pager -->
<div class="hint-list-box" v-if="paging !== 'none'">
<ul class="hint-list" :class="{center: paging === 'center', right: paging === 'right' }">
<li class="item" v-for="item in hintLen" :key="item"
:class="{active: (item === index && loop === true) || (!loop && item === index + 1)}">
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
name: 'my-swiper',
data() {
return {
startX: 0,
endX: 0,
nowLeft: 0,
isClickL: false,
isClickR: false,
length: 0,
index: 0,
width: 0,
resistance: 1,
itemWidth: 0,
timer: null,
autoTimer: null,
zoomTimer: null
}
},
props: {
oHeight: { // Component height settings
type: String,
default: 'auto'
},
nextBtn: { // Whether to display the switch button by default false
type: Boolean,
default: false
},
loop: { // Whether the default playback loop is false
type: Boolean,
default: false
},
paging: { // Whether to display the pager default none No display Optional left, center, right
type: String,
default: 'center'
},
pagingText: { // Whether to display the number of pages Default none No display The input string is prefixed with page number text
type: String,
default: 'none'
},
pagingPosition: { // Page positioning default center In the middle Optional left right
type: String,
default: 'center'
},
defaultIndex: { // Default start rotation index Default 0 Please fill in the length of the element you passed in Numbers
type: Number,
default: 0
},
automation: { // Whether to automatically rotate by 0 It doesn't rotate automatically Default 3000 Every time 3000ms One round
type: Number,
default: 0
},
zoom: { // Whether to start zoom Pattern To be used with the width of the subcomponent Must be in loop On in mode
type: Boolean,
default: false
},
retract: { // Whether to indent To be used with the width of the subcomponent Must be in loop On in mode
type: Boolean,
default: false
}
},
methods: {
// Trigger method when finger click , It mainly records when the finger starts to slide x Coordinates are used to calculate the difference between the end of the slide and the beginning of the slide , Clear on touch Auto rotation and the timer of carousel animation
startMove(e) {
clearInterval(this.timer) // Clear the rotation animation timer
clearInterval(this.autoTimer) // Clear auto carousel timer
this.startX = e.targetTouches[0].clientX // When you get a touch x coordinate
this.nowLeft = this.$refs.sliderBox.offsetLeft // Record the current slider left value
},
// It's triggered when you drag your finger , Slide animation
slider(nowX) {
if (this.$refs.sliderBox.offsetLeft > 0 && !this.loop) { // Not in loop mode When the first element is dragged to the right, the velocity decreases
this.resistance += 0.03
window.console.log(55555)
this.$refs.sliderBox.style.left = (nowX - this.startX) / this.resistance + 'px'
return
} else if (this.$refs.sliderBox.offsetLeft < -this.maxLeft && !this.loop) { // Not in loop mode When the last element is dragged to the left, the velocity decreases
this.resistance += 0.03
this.$refs.sliderBox.style.left = this.nowLeft + (nowX - this.startX) / this.resistance + 'px'
return
}
this.$refs.sliderBox.style.left = this.nowLeft + (nowX - this.startX) + 'px'
},
// According to the subelements Slider width
getItemDom() {
let itemArr = Array.prototype.slice.call(this.$refs.sliderBox.children, 0)
this.length = this.$refs.sliderBox.children.length
itemArr.forEach((ele) => {
this.width += parseFloat(ele.style.width)
})
},
// zoom Slide animation in mode
zoomMove(nowX) {
if (nowX - this.startX < 0) {
let scale = (-(nowX - this.startX) * 0.001) + 0.8 > 1 ? 1 : (-(nowX - this.startX) * 0.001) + 0.8
let opacity = (-(nowX - this.startX) * 0.001) + 0.5 > 1 ? 1 : (-(nowX - this.startX) * 0.0015) + 0.5
this.$refs.sliderBox.children[this.index + 1].style.transform = 'scale(' + scale + ')'
this.$refs.sliderBox.children[this.index + 1].style.opacity = opacity
} else {
let scale = ((nowX - this.startX) * 0.001) + 0.8 > 1 ? 1 : ((nowX - this.startX) * 0.001) + 0.8
let opacity = ((nowX - this.startX) * 0.001) + 0.5 > 1 ? 1 : ((nowX - this.startX) * 0.0015) + 0.5
this.$refs.sliderBox.children[this.index - 1].style.transform = 'scale(' + scale + ')'
this.$refs.sliderBox.children[this.index - 1].style.opacity = opacity
}
},
// This method is triggered when the finger drags
move(e) {
let nowX = e.targetTouches[0].clientX
this.slider(nowX) // Call the slide animation function
this.zoom && this.zoomMove(nowX) // call zoom Animation functions
},
// Trigger at the end of the drag The method
endMove(e) {
this.endX = e.changedTouches[0].clientX
if (this.resistance !== 1) this.resistance = 1
// Judge the drag distance Whether to change index
if (this.distance > 50) {
this.handleLast('touch')
} else if (this.distance < -50) {
this.handleNext('touch')
} else {
this.animation(this.$refs.sliderBox, this.target)
}
// In auto rotation Drag to end, restart timer
this.autoTimer = this.automation ? this.handleAuto() : null
},
// Switch to the next function , Mainly to change index Mode switching
handleLast(isTouch) {
this.isClickL = true
if (!this.loop) {
if (!this.index && isTouch !== 'touch') {
this.index = this.length - 1
} else if (this.index) {
this.index--
} else {
this.animation(this.$refs.sliderBox, this.target)
}
} else {
if (this.index === 1) {
this.transposition()
this.index = this.length - 2
} else {
this.index--
}
}
this.zoom && this.$refs.sliderBox && this.zoomAnimation(this.$refs.sliderBox.children[this.index])
setTimeout(() => {
this.isClickL = false
}, 300)
},
// Switch to the previous function , Mainly to change index Mode switching
handleNext(isTouch) {
this.isClickR = true
if (!this.loop) {
if (this.index === this.length - 1 && isTouch !== 'touch') {
this.index = 0
} else if (this.index !== this.length - 1) {
this.index++
} else {
this.animation(this.$refs.sliderBox, this.target)
}
} else {
if (this.index === this.length - 2) {
this.transposition('isLast')
this.index = 1
} else {
this.index++
}
}
this.zoom && this.$refs.sliderBox && this.zoomAnimation(this.$refs.sliderBox.children[this.index])
setTimeout(() => {
this.isClickR = false
}, 300)
},
// Switch animation
animation(dom, target) {
clearInterval(this.timer)
let origin = null
let speed = null
this.timer = setInterval(() => {
origin = dom.offsetLeft
speed = (target - origin) / 9
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)
if (Math.abs(target - dom.offsetLeft) < 2) {
dom.style.left = target + 'px'
clearInterval(this.timer)
return
}
dom.style.left = origin + speed + 'px'
}, 16)
this.endX = 0
this.startX = 0
if (this.zoom) {
this.isZoomActive()
}
},
// zoom Animation
zoomAnimation(dom) {
clearInterval(this.zoomTimer)
let originScale = Number(this.getDomTransform(dom, 'scale'))
let originOpacity = Number(dom.style.opacity)
if (originScale === 1 && originOpacity === 1) {
clearInterval(this.zoomTimer)
return
}
let speed = 0.02
this.zoomTimer = setInterval(() => {
if (originScale >= 1 && originOpacity >= 1) {
clearInterval(this.zoomTimer)
return
}
originScale += speed
originOpacity += speed
dom.style.transform = originScale > 1 ? `scale(1)` : `scale(${originScale})`
dom.style.opacity = originOpacity
}, 16)
},
// Get elements transform function
getDomTransform(dom, type) {
let transformStr = dom.style.transform
let tarnArr = transformStr.split(' ')
let obj = {}
tarnArr.forEach(item => {
let tempArr = item.split('(')
obj[tempArr[0]] = tempArr[1].slice(0, -1)
})
return type ? obj[type] : obj
},
// loop Pre render function of pattern , I don't think it's very beautiful. The key is to put , Each item in the slider is passed in as a label , I didn't think of a better way , If it's an array, it's better
renderLoop() {
if (this.loop) {
let divArr = Array.prototype.slice.call(this.$refs.sliderBox.children, 0)
let len = divArr.length
let deviceWidth = document.documentElement.clientWidth
let first = divArr[0].cloneNode(true)
let last = divArr[len - 1].cloneNode(true)
this.$refs.sliderBox.appendChild(first)
this.$refs.sliderBox.insertBefore(last, this.$refs.sliderBox.children[0])
setTimeout(() => {
this.$refs.sliderBox.style.left = -(this.defaultIndex + 1) * this.$refs.sliderBox.children[0].offsetWidth + (deviceWidth - this.$refs.sliderBox.children[0].offsetWidth)/2 + 'px'
window.console.log('-----', this.$refs.sliderBox.style.left)
if (this.defaultIndex <= this.length - 1) {
this.index = this.defaultIndex + 1
}
})
} else {
setTimeout(() => {
this.$refs.sliderBox.style.left = -this.defaultIndex * this.$refs.sliderBox.children[0].offsetWidth + 'px'
this.index = this.defaultIndex
})
}
this.getItemDom()
},
// zoom Pattern adjustment
isZoomActive() {
if (this.$refs.sliderBox) {
for (let i = 0; i < this.$refs.sliderBox.children.length; i++) {
if (i !== this.index) {
this.$refs.sliderBox.children[i].style.transform = 'scale(0.8)'
this.$refs.sliderBox.children[i].style.opacity = '0.5'
} else {
this.$refs.sliderBox.children[i].style.transform = 'scale(1)'
this.$refs.sliderBox.children[i].style.opacity = '1'
}
}
}
},
// Transposition function in loop pattern
transposition(isLast) {
if (isLast) {
if (this.$refs.sliderBox) this.$refs.sliderBox.style.left = this.distance + 'px'
return
}
this.$refs.sliderBox.style.left = -(this.length - 1) * this.$refs.sliderBox.children[0].offsetWidth + this.distance + 'px'
},
// Start automatic mode
handleAuto() {
if (this.automation) {
return (setInterval(() => {
this.handleNext()
}, this.automation))
}
}
},
computed: {
// The difference between touching and leaving fingers
distance() {
return this.endX - this.startX
},
// Calculate slider destination
target() {
if (this.swiperWidth - this.$refs.sliderBox.children[0].offsetWidth !== 0 && this.retract) {
return -this.index * this.$refs.sliderBox.children[0].offsetWidth + (this.swiperWidth - this.$refs.sliderBox.children[0].offsetWidth) / 2
}
return -this.index * this.$refs.sliderBox.children[0].offsetWidth
},
// Number of pages
hintLen() {
return this.loop && this.length ? this.length - 2 : this.length
},
// box Width
swiperWidth() {
return this.$refs.swiperBox && this.$refs.swiperBox.offsetWidth
},
// Slide limit value
maxLeft() {
return this.$refs.sliderBox && this.$refs.sliderBox.offsetWidth - this.$refs.sliderBox.children[0].offsetWidth
}
},
watch: {
// monitor index change
index() {
this.animation(this.$refs.sliderBox, this.target)
}
},
mounted() {
this.renderLoop()
this.autoTimer = this.automation ? this.handleAuto() : null
},
beforeDestroy() {
clearInterval(this.timer)
clearInterval(this.autoTimer)
clearInterval(this.zoomTimer)
}
}
</script>
<style lang="scss" scoped>
.swiper-box {
width: 100%;
overflow: hidden;
position: relative;
.swiper-wrapper {
position: relative;
overflow: hidden;
display: flex;
}
.btn-box {
position: absolute;
width: 100%;
top: 50%;
display: flex;
justify-content: space-between;
transform: translateY(-50%);
overflow: hidden;
p {
overflow: hidden;
color: rgba(4, 4, 4, .4);
background-color: rgba(8, 8, 8, .1);
&.click {
background-color: rgba(8, 8, 8, .6);
.iconfont {
color: rgba(4, 4, 4, .6);
}
}
.iconfont {
font-size: .8rem;
}
}
}
.hint-list-box {
position: absolute;
width: 100%;
bottom: .2rem;
.hint-list {
display: flex;
&.center {
justify-content: center;
}
&.right {
justify-content: flex-end;
}
}
.item {
width: .2rem;
height: .2rem;
border-radius: 50%;
background-color: #eeeeec;
margin-left: .2rem;
&.active {
background: linear-gradient(#6a3, #4e6);
}
}
}
.paging-text-box {
position: absolute;
top: .1rem;
text-align: center;
width: 100%;
&.right {
text-align: right;
span {
margin-right: 1rem;
}
}
&.left {
text-align: left;
span {
margin-left: 1rem;
}
}
}
}
</style>

mySwiperItem.vue

<!--
* @Author: yang
* @Date: 2020-11-09 07:04:39
* @LastEditors: yang
* @LastEditTime: 2020-11-09 10:45:21
* @FilePath: \gloud-h5\src\component\index\mySwiperItem.vue
-->
<template>
<div :style="{height: height + 'rem', width: width + 'rem'}" class="item-wrapper" >
<slot :ref="'item' + name"></slot>
</div>
</template>
<script>
export default {
name: "my-swiper-item",
props: {
width: {
type: Number,
required: true
},
height: {
type: String,
default: '4'
}
}
}
</script>
<style scoped>
</style>

It uses css precompile less

npm install --save-dev less less-loader css-loader style-loader

Use
index.vue

<template>
<div class="show-swiper-wrapper">
<p class="show-toast-title"> The carousel shows </p>
<div class="item">
<divider> Base call </divider>
<my-swiper>
<my-swiper-item :width="7.5" v-for="item in list" :key="item.id" >
<img :src="item.img" alt="">
</my-swiper-item>
</my-swiper>
</div>
<div class="item">
<divider> Automatic wheel broadcasting </divider>
<my-swiper :automation="2000" paging="right">
<my-swiper-item :width="7.5" v-for="item in list" :key="item.id">
<img :src="item.img" alt="">
</my-swiper-item>
</my-swiper>
</div>
<div class="item">
<divider> The loop has buttons </divider>
<my-swiper :nextBtn="true" :automation="2000" :loop="true" paging="left">
<my-swiper-item :width="7.5" v-for="item in list" :key="item.id">
<img :src="item.img" alt="">
</my-swiper-item>
</my-swiper>
</div>
<div class="item">
<divider> Indent mode </divider>
<my-swiper :zoom="true" :retract="true" :automation="3000" :oHeight="'3rem'" eight="3" :loop="true" paging="none">
<my-swiper-item :width="5" height="3" v-for="item in list" :key="item.id">
<img :src="item.img" alt="">
</my-swiper-item>
</my-swiper>
</div>
<divider> View source code </divider>
<my-button class="button-item" @button-click="pushLink" text=" see demo Source code " size="lang" />
</div>
</template>
<script>
import MySwiper from './components/slider/mySwiper'
import MySwiperItem from './components/slider/mySwiperItem'
import Divider from './components/divider'
import MyButton from './components/myButton'
export default {
name: 'showSwiper',
components: {
MySwiper,
MySwiperItem,
Divider,
MyButton
},
data() {
return {
// To get a local experiment, you have to change paths
list: [
{
img: require('./static/1.jpg'),
id: 1
},
{
img: require('./static/2.jpg'),
id: 2
},
{
img: require('./static/3.jpg'),
id: 3
},
{
img: require('./static/4.jpg'),
id: 4
}
]
}
},
methods: {
pushLink() {
this.$router.push(`/soundCodeShow${this.$route.fullPath}`)
}
}
}
</script>
<style scoped lang="less">
.show-swiper-wrapper {
display: flex;
flex-direction: column;
align-items: center;
position: relative;
padding-bottom: 1rem;
}
.show-swiper-wrapper .item {
width: 100%;
}
.show-swiper-wrapper .item img {
width: 100%;
height: 100%;
}
</style>

effect :
image.png

版权声明
本文为[yang]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple