在前端項(xiàng)目開發(fā)過程中,文本的復(fù)制粘貼功能經(jīng)常會(huì)被用到。如上圖,將列表中的鏈接地址進(jìn)行復(fù)制,到瀏覽器中粘貼打開。再或者一些網(wǎng)站上,通過按鈕粘貼輸入框中的代碼的功能等等。今天,我們就來講一下,Vue 項(xiàng)目中用于復(fù)制的一個(gè)插件 clipboard。
clipboard官網(wǎng)
數(shù)字化管理平臺(tái)
Vue3+Vite+VueRouter+Pinia+Axios+ElementPlus
個(gè)人博客地址
什么是 clipboard
官網(wǎng):https://clipboardjs.com/
中文:https://www.itxst.com/clipboardjs/tutorial.html
在clipboard.js官網(wǎng)上,有這么一段文字來描述它:
A modern approach to copy text to clipboard
No Flash. No frameworks. Just 3kb gzipped
簡而言之,就是現(xiàn)代化的文本復(fù)制工具,不依賴Flash,不不賴框架,壓縮后僅3kb大小。使用這個(gè)工具,可以快速輕松的實(shí)現(xiàn)文本復(fù)制的功能。
項(xiàng)目可以采用 npm 或者直接下載工具包的方式引入:
直接下載地址:https://github.com/zenorocha/clipboard.js/archive/master.zip
npm 安裝
npm install clipboard --save
CDN引入:
<script src="https://www.itxst.com/package/clipboardjs/clipboard.min.js"></script>
這個(gè)項(xiàng)目中用的方式
clipboard 安裝
npm install clipboard --save
封裝到全局工具中 clipboard.js
import Vue from 'vue'
import Clipboard from 'clipboard'
function clipboardSuccess() {
Vue.prototype.$message.success('復(fù)制成功')
}
function clipboardError() {
Vue.prototype.$message.error('復(fù)制失敗')
}
export default function handleClipboard(text, event) {
const clipboard = new Clipboard(event.target, {
text: () => text
})
clipboard.on('success', () => {
clipboardSuccess()
clipboard.destroy()
})
clipboard.on('error', () => {
clipboardError()
clipboard.destroy()
})
clipboard.onClick(event)
}
組件中使用
# template 模板代碼
<el-table-column prop="webUrl" label="H5鏈接" width="300">
<template slot-scope="scope">
<el-link
:underline="false"
type="primary"
@click="handleCopy(scope.row.webUrl, $event)"
>{{ scope.row.webUrl }}
</el-link>
</template>
</el-table-column>
# 腳本代碼
import clip from '@/utils/clipboard'
handleCopy(text, event) {
clip(text, event)
}
數(shù)字化管理平臺(tái)
Vue3+Vite+VueRouter+Pinia+Axios+ElementPlus
Vue權(quán)限系統(tǒng)案例
個(gè)人博客地址
網(wǎng)上的另外一種指令用法(未驗(yàn)證)
安裝同上,引入同上
import Clipboard from 'clipboard'
三個(gè)指令:
- v-clipboard:copy - copy 要復(fù)制的內(nèi)容 cut 要剪貼的內(nèi)容
- v-clipboard:success 復(fù)制或剪貼成功的回調(diào)函數(shù)
- v-clipboard:error 復(fù)制或剪貼失敗的回調(diào)函數(shù)
代碼:
<a-modal
v-model="visible"
title="鏈接"
@ok="handleOk"
>
<template #footer>
<a-button key="submit" type="primary" @click="handleOk">好的</a-button>
</template>
<p>分享鏈接可以邀請(qǐng)其他人</p>
<p>
<a-tag color="blue">{{ roomShareUrl }}</a-tag>
<a class="fs12" v-clipboard:copy="roomShareUrl" v-clipboard:success="onCopy">復(fù)制
</a>
</p>
</a-modal>
data() {
return {
visible: false,
roomShareUrl: ''
}
},
methods: {
// 初始化方法
show(roomId) {
roomShare(roomId).then(res => {
if (res.success) {
this.visible = true
console.log(res.data)
this.roomShareUrl = res.data
}
})
},
handleOk() {
this.roomShareUrl = ''
this.visible = false
},
onCopy: function(e) {
message.success('復(fù)制成功')
}
}
附錄:原生得剪切板操作
瀏覽器允許 JavaScript 腳本讀寫剪貼板,自動(dòng)復(fù)制或粘貼內(nèi)容。
一般來說,腳本不應(yīng)該改動(dòng)用戶的剪貼板,以免不符合用戶的預(yù)期。但是,有些時(shí)候這樣做確實(shí)能夠帶來方便,比如"一鍵復(fù)制"功能,用戶點(diǎn)擊一下按鈕,指定的內(nèi)容就自動(dòng)進(jìn)入剪貼板。
目前,一共有三種方法可以實(shí)現(xiàn)剪貼板操作。
1. Document.execCommand()方法
Document.execCommand()是操作剪貼板的傳統(tǒng)方法,各種瀏覽器都支持。
它支持復(fù)制、剪切和粘貼這三個(gè)操作。
-
document.execCommand(‘copy’)(復(fù)制)
復(fù)制時(shí),先選中文本,然后調(diào)用document.execCommand(‘copy’),選中的文本就會(huì)進(jìn)入剪貼板。const inputElement = document.querySelector('#input'); inputElement.select(); document.execCommand('copy');
注意,復(fù)制操作最好放在事件監(jiān)聽函數(shù)里面,由用戶觸發(fā)(比如用戶點(diǎn)擊按鈕)。如果腳本自主執(zhí)行,某些瀏覽器可能會(huì)報(bào)錯(cuò)。
-
document.execCommand(‘cut’)(剪切)
-
document.execCommand(‘paste’)(粘貼)
粘貼時(shí),調(diào)用document.execCommand(‘paste’),就會(huì)將剪貼板里面的內(nèi)容,輸出到當(dāng)前的焦點(diǎn)元素中const pasteText = document.querySelector('#output'); pasteText.focus(); document.execCommand('paste');
Document.execCommand()方法雖然方便,但是有一些缺點(diǎn)。
首先,它只能將選中的內(nèi)容復(fù)制到剪貼板,無法向剪貼板任意寫入內(nèi)容。
其次,它是同步操作,如果復(fù)制/粘貼大量數(shù)據(jù),頁面會(huì)出現(xiàn)卡頓。有些瀏覽器還會(huì)跳出提示框,要求用戶許可,這時(shí)在用戶做出選擇前,頁面會(huì)失去響應(yīng)。
為了解決這些問題,瀏覽器廠商提出了異步的 Clipboard API。
2. 異步的 Clipboard API
Clipboard API 是下一代的剪貼板操作方法,比傳統(tǒng)的document.execCommand()方法更強(qiáng)大、更合理。
它的所有操作都是異步的,返回 Promise 對(duì)象,不會(huì)造成頁面卡頓。而且,它可以將任意內(nèi)容(比如圖片)放入剪貼板。
navigator.clipboard屬性返回 Clipboard 對(duì)象,所有操作都通過這個(gè)對(duì)象進(jìn)行。
const clipboardObj = navigator.clipboard;
如果navigator.clipboard屬性返回undefined,就說明當(dāng)前瀏覽器不支持這個(gè) API。
由于用戶可能把敏感數(shù)據(jù)(比如密碼)放在剪貼板,允許腳本任意讀取會(huì)產(chǎn)生安全風(fēng)險(xiǎn),所以這個(gè) API 的安全限制比較多。
首先,Chrome 瀏覽器規(guī)定,只有 HTTPS 協(xié)議的頁面才能使用這個(gè) API。不過,開發(fā)環(huán)境(localhost)允許使用非加密協(xié)議。
其次,調(diào)用時(shí)需要明確獲得用戶的許可。權(quán)限的具體實(shí)現(xiàn)使用了 Permissions API,跟剪貼板相關(guān)的有兩個(gè)權(quán)限:clipboard-write(寫權(quán)限)和clipboard-read(讀權(quán)限)。"寫權(quán)限"自動(dòng)授予腳本,而"讀權(quán)限"必須用戶明確同意給予。也就是說,寫入剪貼板,腳本可以自動(dòng)完成,但是讀取剪貼板時(shí),瀏覽器會(huì)彈出一個(gè)對(duì)話框,詢問用戶是否同意讀取。
另外,需要注意的是,腳本讀取的總是當(dāng)前頁面的剪貼板。這帶來的一個(gè)問題是,如果把相關(guān)的代碼粘貼到開發(fā)者工具中直接運(yùn)行,可能會(huì)報(bào)錯(cuò),因?yàn)檫@時(shí)的當(dāng)前頁面是開發(fā)者工具的窗口,而不是網(wǎng)頁頁面。
(async () => {
const text = await navigator.clipboard.readText();
console.log(text);
})();
如果你把上面的代碼,粘貼到開發(fā)者工具里面運(yùn)行,就會(huì)報(bào)錯(cuò)。因?yàn)榇a運(yùn)行的時(shí)候,開發(fā)者工具窗口是當(dāng)前頁,這個(gè)頁面不存在 Clipboard API 依賴的 DOM 接口。一個(gè)解決方法就是,相關(guān)代碼放到setTimeout()里面延遲運(yùn)行,在調(diào)用函數(shù)之前快速點(diǎn)擊瀏覽器的頁面窗口,將其變成當(dāng)前頁。
setTimeout(async () => {
const text = await navigator.clipboard.readText();
console.log(text);
}, 2000);
上面代碼粘貼到開發(fā)者工具運(yùn)行后,快速點(diǎn)擊一下網(wǎng)頁的頁面窗口,使其變?yōu)楫?dāng)前頁,這樣就不會(huì)報(bào)錯(cuò)了。
3. copy事件和paste事件
Clipboard 對(duì)象提供了四個(gè)方法,用來讀寫剪貼板。它們都是異步方法,返回 Promise 對(duì)象。
-
Clipboard.readText()
Clipboard.readText()方法用于復(fù)制剪貼板里面的文本數(shù)據(jù)。async function getClipboardContents() { try { const text = await navigator.clipboard.readText(); console.log('Pasted content: ', text); } catch (err) { console.error('Failed to read clipboard contents: ', err); } }
- Clipboard.read()
Clipboard.read()方法用于復(fù)制剪貼板里面的數(shù)據(jù),可以是文本數(shù)據(jù),也可以是二進(jìn)制數(shù)據(jù)(比如圖片)。該方法需要用戶明確給予許可。
該方法返回一個(gè) Promise 對(duì)象。一旦該對(duì)象的狀態(tài)變?yōu)?resolved,就可以獲得一個(gè)數(shù)組,每個(gè)數(shù)組成員都是 ClipboardItem 對(duì)象的實(shí)例。
async function getClipboardContents() {
try {
const clipboardItems = await navigator.clipboard.read();
for (const clipboardItem of clipboardItems) {
for (const type of clipboardItem.types) {
const blob = await clipboardItem.getType(type);
console.log(URL.createObjectURL(blob));
}
}
} catch (err) {
console.error(err.name, err.message);
}
}
-
Clipboard.writeText()
Clipboard.writeText()方法用于將文本內(nèi)容寫入剪貼板。
async function copyPageUrl() {
try {
await navigator.clipboard.writeText(location.href);
console.log('Page URL copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
-
Clipboard.write()
Clipboard.write()方法用于將任意數(shù)據(jù)寫入剪貼板,可以是文本數(shù)據(jù),也可以是二進(jìn)制數(shù)據(jù)。
該方法接受一個(gè) ClipboardItem 實(shí)例作為參數(shù),表示寫入剪貼板的數(shù)據(jù)。try { const imgURL = 'https://dummyimage.com/300.png'; const data = await fetch(imgURL); const blob = await data.blob(); await navigator.clipboard.write([ new ClipboardItem({ [blob.type]: blob }) ]); console.log('Image copied.'); } catch (err) { console.error(err.name, err.message); }
上面示例中,腳本向剪貼板寫入了一張圖片。注意,Chrome 瀏覽器目前只支持寫入 PNG 格式的圖片。
ClipboardItem()是瀏覽器原生提供的構(gòu)造函數(shù),用來生成ClipboardItem實(shí)例,它接受一個(gè)對(duì)象作為參數(shù),該對(duì)象的鍵名是數(shù)據(jù)的 MIME 類型,鍵值就是數(shù)據(jù)本身。
下面的例子是將同一個(gè)剪貼項(xiàng)的多種格式的值,寫入剪貼板,一種是文本數(shù)據(jù),另一種是二進(jìn)制數(shù)據(jù),供不同的場合粘貼使用。function copy() { const image = await fetch('kitten.png'); const text = new Blob(['Cute sleeping kitten'], {type: 'text/plain'}); const item = new ClipboardItem({ 'text/plain': text, 'image/png': image }); await navigator.clipboard.write([item]); }
-
copy 事件,cut 事件
用戶向剪貼板放入數(shù)據(jù)時(shí),將觸發(fā)copy事件。
下面的示例是攔截用戶的復(fù)制操作,將指定內(nèi)容放入剪貼板。const clipboardItems = []; document.addEventListener('copy', async (e) => { e.preventDefault(); try { let clipboardItems = []; for (const item of e.clipboardData.items) { if (!item.type.startsWith('image/')) { continue; } clipboardItems.push( new ClipboardItem({ [item.type]: item, }) ); await navigator.clipboard.write(clipboardItems); console.log('Image copied.'); } } catch (err) { console.error(err.name, err.message); } });
上面示例中,先使用e.preventDefault()取消了剪貼板的默認(rèn)操作,然后由腳本接管復(fù)制操作。
cut事件則是在用戶進(jìn)行剪切操作時(shí)觸發(fā),它的處理跟copy事件完全一樣,也是從Event.clipboardData屬性拿到剪切的數(shù)據(jù)。文章來源:http://www.zghlxwxcb.cn/news/detail-804280.html -
paste 事件
用戶使用剪貼板數(shù)據(jù),進(jìn)行粘貼操作時(shí),會(huì)觸發(fā)paste事件。
下面的示例是攔截粘貼操作,由腳本將剪貼板里面的數(shù)據(jù)取出來。文章來源地址http://www.zghlxwxcb.cn/news/detail-804280.htmldocument.addEventListener('paste', async (e) => { e.preventDefault(); const text = await navigator.clipboard.readText(); console.log('Pasted text: ', text); });
到了這里,關(guān)于【Vue 插件篇】粘貼板插件 clipboard.js 與 原生JS中的復(fù)制、剪切、粘貼的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!