vue项目做一键复制页面内容到粘贴板功能
你在项目里面是否遇到过 页面数据过多,但是你想将页面的数据一下复制出来 并将将数据粘贴到微信,扣扣或者钉钉里面呢?怎么办呢?请往下看吧!
技术要点 v-clipboard
安装插件
yarn add vue-clipboard2
在main.js中配置
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)
// HTML
<div
v-clipboard:copy="shareTxt" // 复制生成的数据
v-clipboard:success="onCopy" // 复制成功
v-clipboard:error="onError" // 复制失败
class="margin_button"
@click="copyData"
>
复制
</div>
// javascript
// 一键分享的数据
getshareTxt() {
this.shareTxt =
`项目初判:${this.shareTxtFormat(this.name)}
有无:
${this.shareTxtFormat(this.mapHaveOrNotHave(this.scoutingObj.itInvestigation.determineCoreReason))}
所属板块:
${this.shareTxtFormat(this.mapPlateId(this.scoutingObj.itInvestigation.determineCoreReason))}
`
},
// 复制成功
onCopy(e) {
this.$message({
type: 'success',
message: '生成文字版成功!请到微信或者钉钉对话框中,粘贴使用'
})
},
// 复制失败
onError(e) {
this.$message({
type: 'error',
message: '生成文字版失败!'
})
},
由于页面可能会出现一下不是你想要的现成的数据,如有富文本框的加入,就会把标签给复制出来,还有下拉框的过滤,数字字符的匹配都需要一点一点处理,这里也放在这里吧,图个方便!
// 格式话复制的数据
shareTxtFormat(val, type) {
if (!val) {
return '--'
}
// 去除富文本框出现的HTML标签
let ccc = val.toString().replace(/<[^>]+>/g, '')
return this.keepInteger(ccc, type)
},
keepInteger(value, type) {
if (!value && value !== 0) return ''
let intPart
if (!type) {
return value
} else if (type == 3) {
intPart = Number(value).toFixed(0)
} else if (type == 1) {
intPart = Number(value).toFixed(1) // 保留1位小数
} else if (type == 2) {
intPart = Number(value).toFixed(2) // 保留2位小数
}
return intPart
},
// 有无过滤(使用三元适合比较少的情况)
mapHaveOrNotHave(val) {
return val == 1 ? '有' : val != 1 ? '无' : ''
},
//
// 板块过滤(碰到比较多的情况就需要做数组的匹配过滤了 此处只是举例子 具体情况看你的项目)
mapPlateId() {
const cityId = "234725892"
getPlateList(cityId).then(res => {
if (res.data.length) {
let aaa = res.data.find(item => {
// 此处 this.plateId 是从后端获取到的
return item.plateId == this.plateId ? item.name : ''
})
}
})
},
小结:
其实这个功能是比较简单的,就是v-clipboard 三个指令,麻烦的地方在于数据的过滤,所以要是数据比较多的情况下,就需要的你的耐心了