vue实现图片横向拖动滚动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<script>
/**
* by niepeng 2024-07-04 pictures swiper
*/
export default {
props: {
customStyle: {
type: Object,
default: () => ({}),
},
},
data() {
return {
ismousedown: false,
startX: 0,
ml: 0,
offsetX: 0,
}
},
methods: {
reset() {
this.ismousedown = false
this.startX = 0
this.offsetX = 0
},
onMouseDown(e) {
this.startX = e.x
this.ismousedown = true
},
onMouseUp(e) {
this.reset()
},
onMouseLeave() {
if (this.ismousedown) {
this.reset()
}
},
onMouseMove(e) {
if (this.ismousedown) {
const prev = this.offsetX
this.$nextTick(() => {
this.offsetX = e.x - this.startX
let ml = this.ml + this.offsetX - prev
if (ml > 0) ml = 0
if (ml > -(this.$refs.list.scrollWidth - this.$refs.wrapBox.clientWidth)) {
this.ml = ml
}
})
}
},
},
}
</script>

<template>
<div class="swiper-wrap" ref="wrapBox">
<div
ref="list"
class="swiper-main"
:class="{ move: ismousedown }"
:style="{ marginLeft: ml + 'px' }"
@mousedown="onMouseDown"
@mouseup="onMouseUp"
@mousemove="onMouseMove"
@mouseleave="onMouseLeave"
>
<slot />
</div>
</div>
</template>

<style lang="scss" scoped>
.swiper-wrap {
position: relative;
overflow: hidden;
cursor: grab;
padding: 10px;
width: 100%;
}
.swiper-main {
display: flex;
flex-wrap: no-wrap;
}
.swiper-main.move {
cursor: ew-resize;
}
</style>