js、vue2、vue3、uniapp環(huán)境下實(shí)現(xiàn)復(fù)制內(nèi)容到剪貼板的方式代碼
一、主流環(huán)境實(shí)現(xiàn)方法
1. 原生 JavaScript
兼容主流瀏覽器的實(shí)現(xiàn)代碼:
/**
* 原生JS復(fù)制內(nèi)容到剪貼板
* @param {string} text - 要復(fù)制的文本內(nèi)容
* @returns {Promise<boolean>} - 復(fù)制成功/失敗
*/
function copyToClipboard(text) {
// 方案1:使用現(xiàn)代API Clipboard(推薦)
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text)
.then(() => {
alert('復(fù)制成功!');
return true;
})
.catch(err => {
console.error('剪貼板寫入失敗:', err);
alert('復(fù)制失敗,請(qǐng)重試!');
return false;
});
}
// 方案2:降級(jí)方案(兼容老瀏覽器)
const textArea = document.createElement('textarea');
textArea.value = text;
// 隱藏textarea避免頁面閃爍
textArea.style.position = 'fixed';
textArea.style.opacity = 0;
document.body.appendChild(textArea);
textArea.select();
try {
const successful = document.execCommand('copy');
if (successful) {
alert('復(fù)制成功!');
} else {
alert('復(fù)制失敗,請(qǐng)手動(dòng)復(fù)制!');
}
return successful;
} catch (err) {
console.error('execCommand復(fù)制失敗:', err);
alert('復(fù)制失敗,請(qǐng)重試!');
return false;
} finally {
document.body.removeChild(textArea);
}
}
// 調(diào)用示例
document.getElementById('copyBtn').addEventListener('click', () => {
copyToClipboard('這是要復(fù)制的內(nèi)容');
});- 核心邏輯:優(yōu)先使用現(xiàn)代的 navigator.clipboard API(需安全上下文),降級(jí)用 document.execCommand('copy') + 臨時(shí) textarea。
- 前置條件:navigator.clipboard 僅在 HTTPS 或 localhost 下可用。
2. Vue2
選項(xiàng)式 API 實(shí)現(xiàn)代碼:
<template>
<button @click="copyToClipboard('Vue2復(fù)制的內(nèi)容')">復(fù)制內(nèi)容</button>
</template>
<script>
export default {
methods: {
copyToClipboard(text) {
// 復(fù)用原生JS核心邏輯,結(jié)合Vue的響應(yīng)式提示
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text)
.then(() => {
this.$message?.success('復(fù)制成功') || alert('復(fù)制成功');
})
.catch(() => {
this.$message?.error('復(fù)制失敗') || alert('復(fù)制失敗');
});
}
// 降級(jí)方案
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.opacity = 0;
document.body.appendChild(textArea);
textArea.select();
try {
const success = document.execCommand('copy');
this.$message?.[success ? 'success' : 'error']?.(
success ? '復(fù)制成功' : '復(fù)制失敗'
) || alert(success ? '復(fù)制成功' : '復(fù)制失敗');
} catch (err) {
this.$message?.error('復(fù)制失敗') || alert('復(fù)制失敗');
} finally {
document.body.removeChild(textArea);
}
}
}
};
</script>- 核心邏輯:復(fù)用原生 JS 復(fù)制邏輯,結(jié)合 Vue2 全局提示(如 Element UI 的 this.$message)優(yōu)化用戶體驗(yàn)。
3. Vue3
組合式 API + Setup Script 實(shí)現(xiàn)代碼:
<template>
<button @click="copyToClipboard('Vue3復(fù)制的內(nèi)容')">復(fù)制內(nèi)容</button>
</template>
<script setup>
import { ElMessage } from 'element-plus'; // 按需引入U(xiǎn)I庫提示
/**
* Vue3復(fù)制到剪貼板
* @param {string} text - 要復(fù)制的文本
*/
const copyToClipboard = async (text) => {
try {
// 優(yōu)先使用Clipboard API
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
ElMessage.success('復(fù)制成功');
return;
}
// 降級(jí)方案
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.opacity = 0;
document.body.appendChild(textArea);
textArea.select();
const success = document.execCommand('copy');
if (success) {
ElMessage.success('復(fù)制成功');
} else {
ElMessage.error('復(fù)制失敗,請(qǐng)手動(dòng)復(fù)制');
}
document.body.removeChild(textArea);
} catch (err) {
ElMessage.error('復(fù)制失敗,請(qǐng)重試');
}
};
</script>- 核心邏輯:使用 async/await 簡(jiǎn)化異步邏輯,結(jié)合 Vue3 生態(tài)的 UI 庫提示,更貼合 Vue3 編碼風(fēng)格。
4. UniApp
跨端兼容實(shí)現(xiàn)代碼:
<template>
<button @click="copyToClipboard('UniApp復(fù)制的內(nèi)容')">復(fù)制內(nèi)容</button>
</template>
<script setup>
import { uniShowToast } from '@dcloudio/uni-app';
/**
* UniApp跨端復(fù)制到剪貼板
* @param {string} text - 要復(fù)制的文本
*/
const copyToClipboard = (text) => {
// UniApp提供了統(tǒng)一的跨端API,無需自己寫兼容
uni.setClipboardData({
data: text,
success: () => {
uniShowToast({
title: '復(fù)制成功',
icon: 'success'
});
},
fail: () => {
uniShowToast({
title: '復(fù)制失敗',
icon: 'none'
});
}
});
};
</script>- 核心邏輯:直接使用 UniApp 封裝的 uni.setClipboardData API,自動(dòng)適配小程序、App、H5 等端,無需手動(dòng)處理兼容。
5. 微信小程序
原生小程序語法實(shí)現(xiàn)代碼:
<!-- index.wxml -->
<button bindtap="copyToClipboard">復(fù)制內(nèi)容</button>
// index.js
Page({
/**
* 微信小程序復(fù)制到剪貼板
*/
copyToClipboard() {
const text = '微信小程序復(fù)制的內(nèi)容';
wx.setClipboardData({
data: text,
success: () => {
wx.showToast({
title: '復(fù)制成功',
icon: 'success'
});
},
fail: () => {
wx.showToast({
title: '復(fù)制失敗',
icon: 'none'
});
}
});
}
});- 核心邏輯:使用微信小程序原生 API wx.setClipboardData,僅能在微信環(huán)境運(yùn)行,無需處理 DOM 相關(guān)邏輯。
二、各實(shí)現(xiàn)方式優(yōu)缺點(diǎn)對(duì)比
技術(shù)環(huán)境 | 實(shí)現(xiàn)方式核心 | 優(yōu)點(diǎn) | 缺點(diǎn) |
原生 JS | Clipboard API/execCommand | 無框架依賴、靈活性高、純前端實(shí)現(xiàn) | 需手動(dòng)處理兼容、HTTPS 限制、需操作 DOM |
Vue2 | 封裝原生 JS 邏輯 | 貼合 Vue2 語法、可結(jié)合 UI 提示 | 仍需處理瀏覽器兼容、依賴 DOM 環(huán)境 |
Vue3 | 異步封裝原生 JS 邏輯 | 代碼更簡(jiǎn)潔、支持 TS、異步清晰 | 仍需處理瀏覽器兼容、依賴 DOM 環(huán)境 |
UniApp | uni.setClipboardData | 跨端兼容、無需手動(dòng)寫兼容、無 DOM | 依賴 UniApp 框架、性能略低于原生 |
微信小程序 | wx.setClipboardData | 原生支持、無 DOM 操作、適配微信 | 僅能在微信環(huán)境運(yùn)行、無跨端能力 |
三、匯總總結(jié)
核心關(guān)鍵點(diǎn)
- 跨端優(yōu)先選 UniApp
UniApp 的 uni.setClipboardData 是最優(yōu)解,一套代碼適配所有端,無需處理兼容問題。
- 純 Web 端選 Vue3 / 原生 JS
Vue3 實(shí)現(xiàn)更簡(jiǎn)潔,原生 JS 適合無框架場(chǎng)景,優(yōu)先用 navigator.clipboard(HTTPS),降級(jí)用 execCommand。
- 微信專屬選小程序原生 API
wx.setClipboardData 適配微信生態(tài),性能和體驗(yàn)最優(yōu),無需處理 DOM 相關(guān)問題。
選型建議
- 多端應(yīng)用(小程序 / H5 / App):直接用 UniApp 的 uni.setClipboardData。
- 純 Web 端:Vue 項(xiàng)目(Vue2/Vue3)封裝原生 JS 邏輯,純靜態(tài)頁面用原生 JS 兼容方案。
- 微信專屬小程序:用微信原生 wx.setClipboardData。
通用注意事項(xiàng)
- 原生 JS 的 navigator.clipboard 僅在 HTTPS 或 localhost 環(huán)境可用。
- 所有環(huán)境的復(fù)制功能都需用戶主動(dòng)觸發(fā)(如點(diǎn)擊按鈕),無法自動(dòng)復(fù)制(瀏覽器/小程序安全限制)。
- UniApp 和微信小程序的 API 是異步的,需通過 success/fail 回調(diào)處理結(jié)果,不可同步獲取復(fù)制狀態(tài)。
到此這篇關(guān)于js、vue2、vue3、uniapp環(huán)境下實(shí)現(xiàn)復(fù)制內(nèi)容到剪貼板的方式代碼的文章就介紹到這了,更多相關(guān)js、vue2、vue3、uniapp復(fù)制內(nèi)容到剪貼板內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript 未結(jié)束的字符串常量常見解決方法
做JavaScript的時(shí)候,發(fā)現(xiàn)老是出現(xiàn)錯(cuò)誤:“未結(jié)束的字符串常量”. 自己找了下應(yīng)該是傳參數(shù)的時(shí)候,有特殊字符引起的.網(wǎng)上也找了下,也有好多出現(xiàn)這種情況.做下總結(jié),以方便以后查閱.2010-01-01
簡(jiǎn)單談?wù)凧avaScript寄生式組合繼承
寄生組合式繼承,是集寄生式繼承和組合繼承的有點(diǎn)與一身,主要是通過借用構(gòu)造函數(shù)來繼承屬性,通過原型鏈的混成形式來繼承方法,這篇文章主要給大家介紹了關(guān)于JavaScript寄生式組合繼承的相關(guān)資料,需要的朋友可以參考下2021-08-08
js實(shí)現(xiàn)圖片拖動(dòng)改變順序附圖
需要改變多個(gè)元素的位置,可以通過元素拖動(dòng)來實(shí)現(xiàn),下面以圖片拖動(dòng)為例,用jQuery來實(shí)現(xiàn),需要的朋友可以參考下2014-05-05
微信小程序緩存支持二次開發(fā)封裝實(shí)現(xiàn)解析
這篇文章主要介紹了微信小程序緩存支持二次開發(fā)封裝實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12

