1.新建一个copy.js文件
import {
Message
} from 'element-ui';
export default {
bind(el, binding) {
if (binding.modifiers.dblclick) {
el.addEventListener('dblclick', () => handleClick(el.innerText))
el.style.cursor = 'copy'
}
else if (binding.modifiers.icon) {
if (el.hasIcon) return
const iconElement = document.createElement('i')
iconElement.setAttribute('class', 'el-icon-document-copy')
iconElement.setAttribute('style', 'margin-left:5px')
el.appendChild(iconElement)
el.hasIcon = true
iconElement.addEventListener('click', () => handleClick(el.innerText))
iconElement.style.cursor = 'copy'
}
else {
el.addEventListener('click', () => handleClick(el.innerText))
el.style.cursor = 'copy'
}
}
}
function handleClick(text) {
if (!document.getElementById('copyTarget')) {
const copyTarget = document.createElement('input')
copyTarget.setAttribute('style', 'position:fixed;top:0;left:0;opacity:0;z-index:-1000;')
copyTarget.setAttribute('id', 'copyTarget')
document.body.appendChild(copyTarget)
}
const input = document.getElementById('copyTarget')
input.value = text
input.select()
document.execCommand('copy')
Message.success('已成功复制到剪切板')
}
2.进行指定指令注册
import limit from './permission'
import copy from './copy'
const directives = {
copy,
limit
};
export default {
install(Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key]);
});
},
};
3.在main.js 进行引入
import directive from '@/directive/permission'
Vue.use(directive)
4.页面使用
<span v-copy.dblclick> {{ goodsData.ownerCode }}</span> //双击复制
<span v-copy> {{ goodsData.ownerCode }}</span>//单机复制
<span v-copy.icon> {{ goodsData.ownerCode }}</span>//点击icon触发复制