<template>
<div class="copy">
<h3>复制功能</h3>
<input type="text" v-model="msg" />
<div class="text_div" @click="copyText2">点击我可以复制:{{ msg }}</div>
<el-button type="primary" @click="copyText">复制1</el-button>
<el-button type="primary" @click="copyText2">复制2</el-button>
</div>
</template>
<script>
export default {
name: 'Copy',
data() {
return {
msg: '我是需要复制的内容'
};
},
methods: {
// 复制:方法一
copyText() {
let inputDom = document.createElement('textarea') // js创建一个文本框
document.body.appendChild(inputDom) //将文本框暂时创建到实例里面
inputDom.value = this.msg //将需要复制的内容赋值到创建的文本框中
inputDom.select() //选中文本框中的内容
inputDom.focus()
document.execCommand('copy') //执行复制操作
document.body.removeChild(inputDom) //最后移出
this.$message.success('复制成功')
},
// 复制:方法二
copyText2() {
navigator.clipboard.writeText(this.msg)
.then(() => {
this.$message.success('复制成功')
})
.catch(() => {
this.$message.error('复制失败')
})
}
},
};
</script>
<style lang="scss" scoped>
.text_div {
cursor: pointer;
}
</style>
vue 如何实现复制功能
最新推荐文章于 2024-05-14 16:48:08 发布