vue 点击复制 (自定义指令)

该博客介绍了如何在Vue.js项目中利用clipboard库封装一个自定义指令`v-copytext`,实现点击元素即可将指定内容复制到剪切板的功能。在`bind`、`update`和`unbind`生命周期钩子中处理事件监听、文本更新及销毁。当复制成功或失败时,通过$Message组件显示相应提示。
摘要由CSDN通过智能技术生成

安装插件 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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

climsi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值