vue滑动解锁实现
滑动解锁实现思路
滑动解锁功能通常通过监听用户触摸或鼠标事件实现,核心逻辑是验证滑块是否移动到指定位置。以下是基于Vue的实现方法:
基础DOM结构
<template>
<div class="slider-container">
<div class="slider-track">
<div
class="slider-thumb"
@mousedown="startDrag"
@touchstart="startDrag"
:style="{ left: thumbPosition + 'px' }"
></div>
<div class="slider-text">{{ dragText }}</div>
</div>
</div>
</template>
核心逻辑实现
export default {
data() {
return {
isDragging: false,
startX: 0,
currentX: 0,
maxWidth: 300, // 滑动轨道宽度
thumbPosition: 0,
success: false
}
},
computed: {
dragText() {
return this.success ? '验证成功' : '向右滑动验证'
}
},
methods: {
startDrag(e) {
this.isDragging = true
this.startX = e.type.includes('touch') ? e.touches[0].clientX : e.clientX
document.addEventListener('mousemove', this.onDrag)
document.addEventListener('touchmove', this.onDrag, { passive: false })
document.addEventListener('mouseup', this.endDrag)
document.addEventListener('touchend', this.endDrag)
},
onDrag(e) {
if (!this.isDragging) return
const clientX = e.type.includes('touch') ? e.touches[0].clientX : e.clientX
this.currentX = clientX - this.startX
if (this.currentX < 0) this.currentX = 0
if (this.currentX > this.maxWidth) this.currentX = this.maxWidth
this.thumbPosition = this.currentX
},
endDrag() {
this.isDragging = false
document.removeEventListener('mousemove', this.onDrag)
document.removeEventListener('touchmove', this.onDrag)
if (this.thumbPosition >= this.maxWidth - 20) {
this.success = true
} else {
this.thumbPosition = 0
}
}
}
}
样式实现
.slider-container {
width: 350px;
margin: 20px auto;
}
.slider-track {
position: relative;
height: 40px;
background: #f0f0f0;
border-radius: 20px;
overflow: hidden;
}
.slider-thumb {
position: absolute;
width: 40px;
height: 40px;
background: #42b983;
border-radius: 50%;
cursor: grab;
z-index: 2;
}
.slider-text {
position: absolute;
width: 100%;
text-align: center;
line-height: 40px;
color: #666;
user-select: none;
}
进阶功能建议
-
添加验证成功回调
watch: { success(val) { if (val) { this.$emit('verify-success') } } } -
防抖处理 在
endDrag方法中添加延迟重置逻辑,防止误操作 -
动画效果 使用CSS transition实现平滑移动
.slider-thumb { transition: left 0.3s ease; } -
移动端适配 通过
@touchstart和@touchend事件确保移动端兼容性
这种实现方式既保留了原生DOM事件的高响应性,又充分利用了Vue的响应式特性。根据实际需求可以进一步扩展验证逻辑和样式表现。







