element+vue 之自定义指令v-copy复制

1.新建一个copy.js文件

element+vue 之自定义指令v-copy复制_第1张图片

import {
 Message
} from 'element-ui';
export default {
 bind(el, binding) {
  // 双击触发复制
  if (binding.modifiers.dblclick) {
   el.addEventListener('dblclick', () => handleClick(el.innerText))
   el.style.cursor = 'copy'

  }
  // 点击icon触发复制
  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.进行指定指令注册

element+vue 之自定义指令v-copy复制_第2张图片

import limit from './permission' //v-limit 
import copy from './copy' //v-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触发复制

你可能感兴趣的:(vue+element,vue.js,javascript,前端)