vue+element+directive 组件复制功能

184 阅读1分钟
1. copy.js

import Vue from 'vue';

import { Message } from 'element-ui';Vue.directive('myCopy', {  bind(el, { value }) {    el.$value = value;    const clickHandler = () => {      const copyEle = document.createElement('input', { style: { display: 'none' } });      copyEle.value = el.$value;      document.body.appendChild(copyEle);      copyEle.select();      const result = document.execCommand('Copy');      if (result) {        Message({          type: 'success',          message: '复制成功',        });      }      document.body.removeChild(copyEle);    };    el.__vueClickHandler = clickHandler;    el.addEventListener('click', clickHandler);  },  componentUpdated(el, { value }) {    el.$value = value;  },  unbind(el) {    el.removeEventListener('click', el.__vueClickHandler);  },});

2. main.js

import ./copy.js

3. 页面中使用
<el-button class="copy" type="primary" v-myCopy="editorValue">复制</el-button>