一、封装事件(长按事件才需要此文件)
res/modules/util/longpress.js
export default {//长按事件,长按复制到剪切板install(Vue, options = {time: 1000}) {Vue.directive('longpress', {bind: function (el, binding, vNode) {// 确保提供的表达式是函数 if (typeof binding.value !== 'function') {const compName = vNode.context.name;// 将警告传递给控制台 let warn = `[longpress:] provided expression '${binding.expression}' is not afunction, but has to be `;if (compName) { warn += `Found in component '${compName}' ` }console.warn(warn);}let pressTimer = null;// 定义函数处理程序// 创建计时器( 1秒后执行函数 )let start = (e) => {if (e.type === 'click' && e.button !== 0) {return;}if (pressTimer === null) {pressTimer = setTimeout(() => {handler();}, options.time)}}// 取消计时器let cancel = (e) => {if (pressTimer !== null) {clearTimeout(pressTimer);pressTimer = null;}}const handler = (e) => {binding.value(e)};// 添加事件监听器el.addEventListener("mousedown", start);el.addEventListener("touchstart", start);// 取消计时器el.addEventListener("click", cancel);el.addEventListener("mouseout", cancel);el.addEventListener("touchend", cancel);el.addEventListener("touchcancel", cancel);}})}
}
二、全局引用(长按事件才需要此文件)
在main.js中引入
import longPress from "./modules/util/longgpress.js"
Vue.use(longPress, { time: 1000 }) //time:长按时长,可自行定义
三、页面使用
<template><!-- 长按复制 --><div v-longpress="() => copyContent(name)">{{item.订单编号}}</div><!-- 点击复制 --><div >{{item.订单编号}}<img @click="copyContent(name)" src="../../assets/image/copy.png" alt=""></div>
</template>
<script>export default {methods: {copyContent(str) {var input = document.createElement('input');input.setAttribute('readonly', 'readonly'); // 防止手机上弹出软键盘input.setAttribute('value', str);document.body.appendChild(input);input.select();document.execCommand('copy');//复制当前选中文本到剪切板document.body.removeChild(input);this.toast = this.$createToast({txt: '复制成功',type: 'txt'})}}}
</script>