方法一
在Vue中实现长按复制文字的功能可以通过以下步骤来实现:
-
首先,在需要实现长按复制文字的元素上添加一个
@mousedown
事件和一个@mouseup
事件,用于监听鼠标按下和松开的动作。 -
在
@mousedown
事件中,使用setTimeout
函数设置一个定时器,当鼠标按下一定时间后触发。 -
在
@mouseup
事件中,清除之前设置的定时器。 -
在定时器触发的回调函数中,使用
document.execCommand('copy')
方法将需要复制的文字复制到剪贴板中。<template> <div> <p @mousedown="startTimer" @mouseup="clearTimer">长按复制文字</p> </div> </template> <script> export default { methods: { startTimer() { this.timer = setTimeout(() => { document.execCommand('copy'); alert('文字已复制到剪贴板'); }, 1000); // 设置长按时间,单位为毫秒 }, clearTimer() { clearTimeout(this.timer); } } } </script>
方法二
在vue中,使用长按复制文字需要用到两个方法:
touchstart.手指放上去的动作
touchend.手指离开的动作
监听两个方法的间隔时间则可以达到长按触发的效果。
<span @touchstart="start" @touchend="end">长按复制“{{ clubname }}”</span>
data() {
return {
Loop:'', // 定时器
}
},
methods: {
start () {
clearTimeout(this.Loop); //再次清空定时器,防止重复注册定时器
this.Loop = setTimeout(() => {
this.copyText(this.clubname)
}, 1000);//1000也可以改成自己所需要长按的时间
},
end () {
clearTimeout(this.Loop); //清空定时器,防止重复注册定时器
},
copyText(context) {
// 创建输入框元素
let oInput = document.createElement('input');
// 将想要复制的值
oInput.value = context;
// 页面底部追加输入框
document.body.appendChild(oInput);
// 选中输入框
oInput.select();
// 执行浏览器复制命令
document.execCommand('Copy');
// 弹出复制成功信息
Toast('复制成功');//使用的vant组件(import {Toast} from 'vant')
// 复制后移除输入框
oInput.remove();
},
}