vue复制文本组件封装

本文档介绍了一个Vue组件,用于实现点击图标复制文本的功能。组件通过获取元素、创建选区和执行复制命令来完成复制操作,适用于前端开发中需要复制文本的场景。

vue复制文本组件封装

Copy组件

<template>
<div>
    <span>{{text}}</span>
   <i class="el-icon-document-copy" ref="copy" @click="copy"></i>
</div>
</template>
<script>
export default {
    props:{
        text:{
            type:Number|String,
            required: true,
        }
    },
  methods: {
    copy() {
       //获取上一个兄弟节点
      let text = this.$refs.copy.previousSibling;
      // 创建select对象与range对象
      const selection = window.getSelection();
      // 从当前selection对象中移除所有的range对象
      if (selection.rangeCount > 0) selection.removeAllRanges();
      const range = document.createRange();
      // 使 Range 包含某个节点的内容 使用这个 或者下面的selectNode都可以
      range.selectNodeContents(text); // 需要选中的dom节点
      // 这个会有换行
      // range.selectNode(text)
      //  选中
      selection.addRange(range);
      // 执行浏览器复制命令
      document.execCommand("copy");
      //  取消选中
      // selection.removeAllRanges()
    },
  },
};
</script>
<style scoped>
</style>

引用

	<Copy text="Copy组件复制的内容"></Copy>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值