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

177

被折叠的 条评论
为什么被折叠?



