最近写了一个拷贝到剪切板的小组件,觉得很有意思,这里分享下
依赖包
这里使用了clipboard.js 的依赖包
下载
npm install clipboard --save
引入
import clipboard from 'clipboard'
Vue.prototype.clipboard = clipboard
组件
该组件应用在table中,每个 row 都提供一个 copy 按钮,这里可以自定义 copy内容,并且复制在 txt 文件中
<template>
<div class="dis-i-b">
<button
@click="copy"
title="复制信息"
:class="clipboardClass"
>点我复制信息</button>
</div>
</template>
<script>
export default {
props: {
row: { //这里传入 当前row 的信息
type: Object,
required: true,
default: function() {
return {
name: 'wsf',
age: '12',
sex: '男',
id: 1,
}
}
}
},
data() {
return {
columns: ['name', 'age', 'sex', 'id'] //这里定义 需要copy的字段
}
},
methods: {
copy() {
const that = this
const clipboard = new this.clipboard('.' + this.clipboardClass, {
text: function() {
return that.columns.reduce((a, b) => {
return `${a} \r\nb : ${that.row[b]}` //这里 /r/n 是txt文件中的换行
}, '')
}
})
clipboard.on('success', function(e) {
alert('复制通话信息成功到剪切版!')
// console.log(e)
// console.info('Action:', e.action)
// console.info('Text:', e.text)
// console.info('Trigger:', e.trigger)
e.clearSelection()
})
}
},
computed: {
clipboardClass() { // 每行都有唯一的 class
return 'clipboard' + this.row.id
}
}
}
</script>
<style scoped>
.dis-i-b {
display: inline-block;
}
</style>