一键复制功能
文章目录
前言
遇到一个一键复制的功能需求,大概有三种方式,大家一起来看看吧。
一、navigator.clipboard.writeText()
最开始使用navigator.clipboard.writeText('内容')
,在本地没有问题,但是部署到服务器上面就不行了,报错内容Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'writeText')
然后我就换第二种方式了。
二、document.execCommand()
官网:已弃用: 不再推荐使用该特性。虽然一些浏览器仍然支持它,但也许已从相关的 web 标准中移除,也许正准备移除或出于兼容性而保留。请尽量不要使用该特性,并更新现有的代码;参见本页面底部的兼容性表格以指导你作出决定。请注意,该特性随时可能无法正常工作。
但是还是可以用的,我现在用的就是这个。看一下示例代码:
<template>
<el-table
:data="tableData"
@row-dblclick="copyCellContent"
>
<el-table-column
prop="name"
label="姓名"
></el-table-column>
<el-table-column
prop="age"
label="年龄"
></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 25 },
{ name: '王五', age: 30 }
]
};
},
methods: {
copyCellContent(row, column) {
const cellContent = row[column.property];
const tempInput = document.createElement('input');
tempInput.value = cellContent;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand('copy');
document.body.removeChild(tempInput);
this.$message({
message: '已复制单元格内容',
type: 'success'
});
}
}
};
</script>
三、vue-clipboard2插件
1.安装
npm install vue-clipboard2 --save
2.引入并使用 vue-clipboard2
import Vue from 'vue'
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)
3.示例代码
<template>
<div>
<el-table
:data="tableData"
>
<el-table-column
prop="name"
label="姓名"
>
<template slot-scope="{ row }">
<span v-clipboard:copy="row.name" @success="handleCopySuccess">复制</span>
</template>
</el-table-column>
<el-table-column
prop="age"
label="年龄"
></el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 25 },
{ name: '王五', age: 30 }
]
};
},
methods: {
handleCopySuccess() {
this.$message({
message: '已复制到剪贴板',
type: 'success'
});
}
}
};
</script>
总结
学海无涯哇!!!
[不想加班]