clipboard.js是一款輕量級(jí)的實(shí)現(xiàn)復(fù)制文本到剪貼板功能的JavaScript插件。通過(guò)該插件可以將輸入框汹族,文本域锚国,DIV元素中的文本等文本內(nèi)容復(fù)制到剪貼板中,clipboard.js 是一個(gè)不依賴(lài) Flash,將文本復(fù)制到剪貼板的插件俊卤,僅僅 2kb嫩挤。
下面簡(jiǎn)單介紹一下它的使用步驟:
1.安裝
npm install clipboard --save
2.在項(xiàng)目根目錄下創(chuàng)建一個(gè)文件夾,在里面封裝clipboard.js相關(guān)的代碼
比如:plugin/copy.js
//copy.js
//拷貝插件 kay
// import iView from 'iview';
import Clipboard from 'clipboard';
let CopyText = new Object();
CopyText.install = function (Vue, options) {
console.log(Vue, '拷貝')
// 4. 添加實(shí)例方法
// text, 要copy的文本
// success, 成功回調(diào)函數(shù)
// error 失敗回調(diào)函數(shù)
Vue.prototype.$CopyText = function (text, success, error) {
// 邏輯...
let oCopyBtn = document.createElement('button');
oCopyBtn.setAttribute('id', 'copy-btn');
oCopyBtn.setAttribute('data-clipboard-text', text);
document.body.appendChild(oCopyBtn);
var clipboard = new Clipboard('#copy-btn');
clipboard.on('success', e => {
success(e);
// console.log('復(fù)制成功');
// iView.Message.success(`復(fù)制成功消恍!`);
// 釋放內(nèi)存
clipboard.destroy();
//移除節(jié)點(diǎn)
document.body.removeChild(oCopyBtn);
});
clipboard.on('error', e => {
error(e);
// 不支持復(fù)制
//console.log('該瀏覽器不支持自動(dòng)復(fù)制')
// iView.Message.error(`復(fù)制失斊裾选!`);
// 釋放內(nèi)存
clipboard.destroy();
//移除節(jié)點(diǎn)
document.body.removeChild(oCopyBtn);
});
//模擬點(diǎn)擊
oCopyBtn.click();
}
};
export default CopyText;
3.在main.js中使用插件
import CopyText from './plugin/copy.js';
//...你的其它代碼
Vue.use(CopyText);
4.在vue組件中使用
比如在About.vue
<template>
<div>
<!-- Target -->
<input id="foo" value="https://github.com/zenorocha/clipboard.js.git" />
<!-- Trigger -->
<el-button
type="primary"
style="color: white"
class="btn"
@click="handleCopy"
>
點(diǎn)擊復(fù)制
</el-button>
</div>
</template>
<script>
export default {
name: "",
data() {
return {
value: new Date(),
};
},
components: {},
methods: {
handleCopy() {
var text = document.getElementById("foo").value;
this.$CopyText(
// 要拷貝的文本,
text,
(e) => {
//something to do
this.$message.success("復(fù)制成功狠怨!"); //例:iview ui框架的提示
},
(e) => {
//something to do
this.$message.error("復(fù)制失斣及 !");
}
);
},
},
};
</script>
<style>
span {
color: white;
}
</style>
這樣就將input輸入框中的內(nèi)容復(fù)制到剪切板了