vue实现长按删除
Vue 实现长按删除功能
在 Vue 中实现长按删除功能,可以通过监听 touchstart 和 touchend 事件或 mousedown 和 mouseup 事件来实现。以下是具体实现方法:

监听触摸或鼠标事件
<template>
<div
@mousedown="startPress"
@mouseup="endPress"
@touchstart="startPress"
@touchend="endPress"
>
长按我删除
</div>
</template>
<script>
export default {
data() {
return {
pressTimer: null,
pressDuration: 2000 // 长按时间阈值(毫秒)
}
},
methods: {
startPress(e) {
// 阻止默认行为,避免触发点击事件
e.preventDefault()
// 设置定时器
this.pressTimer = setTimeout(() => {
this.deleteItem()
}, this.pressDuration)
},
endPress() {
// 清除定时器
clearTimeout(this.pressTimer)
},
deleteItem() {
// 执行删除操作
console.log('删除操作')
}
}
}
</script>
优化用户体验
为避免误触,可以添加视觉反馈,例如在长按时改变元素样式:

<template>
<div
@mousedown="startPress"
@mouseup="endPress"
@touchstart="startPress"
@touchend="endPress"
:class="{ 'pressing': isPressing }"
>
长按我删除
</div>
</template>
<script>
export default {
data() {
return {
isPressing: false,
pressTimer: null,
pressDuration: 2000
}
},
methods: {
startPress(e) {
e.preventDefault()
this.isPressing = true
this.pressTimer = setTimeout(() => {
this.deleteItem()
this.isPressing = false
}, this.pressDuration)
},
endPress() {
this.isPressing = false
clearTimeout(this.pressTimer)
},
deleteItem() {
console.log('删除操作')
}
}
}
</script>
<style>
.pressing {
background-color: #f0f0f0;
}
</style>
移动端兼容性
对于移动端,确保正确处理触摸事件:
methods: {
startPress(e) {
if (e.type === 'touchstart') {
// 阻止触摸滚动
e.preventDefault()
}
this.isPressing = true
this.pressTimer = setTimeout(() => {
this.deleteItem()
this.isPressing = false
}, this.pressDuration)
}
}
注意事项
- 长按时间阈值(
pressDuration)可根据需求调整。 - 在移动端,
touchstart和touchend事件更可靠。 - 清除定时器是必要的,避免内存泄漏。






