copyText(text) {
var textarea = document.createElement("input"); //创建input对象
var currentFocus = document.activeElement; //当前获得焦点的元素
document.body.appendChild(textarea); //添加元素
textarea.value = text;
textarea.focus();
if (textarea.setSelectionRange)
textarea.setSelectionRange(0, textarea.value.length);
//获取光标起始位置到结束位置
else textarea.select();
try {
var flag = document.execCommand("copy"); //执行复制
} catch (eo) {
var flag = false;
}
document.body.removeChild(textarea); //删除元素
currentFocus.focus();
return flag;
},
handleCopyClick(address, officialAccountId) { this.$api.createEAHome.gethomEnvHtml().then(res => { console.log("gethomEnvHtml", res); let str1 = res.data.resMsg; let str2 = "/#/posterCenter?channelid=" + officialAccountId + "&address=" + address; let str = str1 + str2; let flag = this.copyText(str); //传递文本 this.$message({ type: flag ? "success" : "error", message: flag ? "复制成功!" : "复制失败!" }); }); },
方法2:vue中使用vue-clipboard2
安装:
npm install --save vue-clipboard2
main.js里面导入并使用:
import VueClipboard from "vue-clipboard2";
Vue.use(VueClipboard);
<template>
<el-button v-clipboard:copy=' urlHeader+ scope.row.officialAccountId + "&address=" + scope.row.address ' v-clipboard:success="onCopy" v-clipboard:error="onError" type="primary" size="small" >复制链接</el-button > </template>
props: { urlHeader: { type: String, default: () => "" } },
使用组件:
<pagelistManage :urlHeader="urlHeader" v-if="urlHeader.length > 0" ></pagelistManage>
getCopyUrl() { console.log("getCopyUrl") this.$api.createEAHome.gethomEnvHtml().then(res => { console.log("gethomEnvHtml", res); if(res.status == "200"){ this.urlHeader = res.data.resMsg + '/#/signing?channelid= '; }else{ this.$message(res.data.resMsg) } }); },
onCopy() {
this.$message("复制成功");
},
onError() {
this.$message("复制失败");
},