安装插件 clipboard
npm install clipboard --save
封装成指令
//directive/copytext.js 文件 基于使用vue+iview的项目
import Clipboard from "clipboard";
import Vue from "vue";
export default {
bind: (el, binding = {}, vnode) => {
const clipboard = new Clipboard(el, {
text: () => binding.value
});
const Message = Vue.prototype.$Message;
clipboard.on("success", e => {
Message.success(e.text + " 已复制到剪切板");
});
clipboard.on("error", e => {
Message.error("复制失败");
});
if (el) {
el.__clipboard__ = clipboard;
el.style.cursor = "pointer";
el.title = el.title || "点击复制";
el.onmouseover = () => {
el.style.color = "#4395FF";
};
el.onmouseout = () => {
el.style.color = "";
};
}
},
update: (el, binding, vnode) => {
el.__clipboard__.text = () => binding.value;
},
unbind: (el, binding) => {
if (!el) return;
el.__clipboard__ && el.__clipboard__.destroy();
delete el.__clipboard__;
}
};
//directive/index.js
import copytext from "./copytext";
const importDirective = Vue => {
Vue.directive("copytext", copytext);
};
export default importDirective;
//main.js
import importDirective from '@/directive'
import Vue from 'vue'
/**
* 注册指令
*/
importDirective(Vue)
使用
<span v-copytext="value">{{ value }}</span>