在实际开发中,会遇到实现复制粘贴的功能,这里利用vue中solt插槽来实现!
1.组件代码:copy.vue
<template>
<div class="text-copy-container">
<slot></slot>
<i v-if="btn === 'icon'" class="el-icon-document-copy" @click="copyContent()"></i>
<el-button v-if="btn === 'button'" type="primary" icon="el-icon-document-copy" @click="copyContent()">复制</el-button>
</div>
</template>
<script>
export default {
props: {
btn: {
type: String,
default: 'icon'
}
},
data() {
return {};
},
mounted() {
},
updated() {
this.$slots.default[0].elm.style.color = '#606266';
},
methods: {
copyContent() {
this.inputElement = document.getElementById('copy-temp-textarea');
if(!this.inputElement) {
this.inputElement = document.createElement('textarea');
this.inputElement.id = "copy-temp-textarea";
this.inputElement.style.position = 'fixed';
this.inputElement.style.bottom = 0;
this.inputElement.style.left = 0;
this.inputElement.style.opacity = 0;
this.inputElement.style['z-index'] = 0;
document.body.appendChild(this.inputElement);
}
try {
let elm = this.$slots.default[0].elm;
let innerContent = '';
if(elm.children && elm.children.length > 0) {
for(let i = 0; i < elm.children.length; i++) {
innerContent += elm.children[i].innerText + '\x0A';
}
}else {
innerContent = elm.innerText;
}
this.inputElement.value = innerContent;
this.inputElement.select();
document.execCommand("Copy");
this.$message.success("复制成功");
elm.style.color = '#0dbd06';
} catch {
this.$message.error("复制失败");
} finally {
this.inputElement.remove();
}
}
}
}
</script>
<style lang="less" scoped>
.text-copy-container {
word-break: break-all;
word-wrap: break-word;
}
</style>
2.引用
import TextCopy from "@component/copy";
components: {
"text-copy": TextCopy
},
<text-copy>
<span>点击我就可以复制啦!!</span>
</text-copy>