Vue3实现剪贴板功能
1.新增依赖
"vue-clipboard2": "^0.3.3"
2.main.js导入和使用依赖
import VueClipBoard from "vue-clipboard2";
createApp(App)
.use(VueClipBoard)
.mount("#app");
3.导入syncHandle和proxy
import { getCurrentInstance } from "vue"; import { syncHandle } from "@/utils/util.js"; const { proxy } = getCurrentInstance();
4.定义syncHandle函数
// util.js export function syncHandle(func) { let timer = setTimeout(async () => { await func(); clearTimeout(timer); }, 0); }
5.实现剪贴板功能(兼容安卓和ios)
syncHandle(() => { proxy.$copyText(url).then( (success) => { Toast.success("下载链接已复制到剪贴板,请使用浏览器下载"); }, (err) => { Toast.fail("复制失败"); } ); });
在项目中使用示例:
const getDownloadToken = () => { const toast = Toast.loading({ duration: 0, forbidclick: true, }); return new Promise((resolve, reject) => { TaskApi.getDownloadToken({ workId: sessionStorage.workId }) .then((response) => { toast.close(); const data = response.data; if (data.code === 200) { const token = data.data; let host = ""; if (import.meta.env.MODE == "production") host = location.protocol + "//" + location.host; const url = `${host}${ import.meta.env.VITE_APP_BASE_API }/actkapwork/downloadWorkOrder?workId=${ sessionStorage.workId }&token=${token}`; console.log(url); // proxy.$copyText(url).then(() => { // Toast.success("下载链接已复制到剪贴板,请使用浏览器下载"); // }); syncHandle(() => { proxy.$copyText(url).then( (success) => { Toast.success("下载链接已复制到剪贴板,请使用浏览器下载"); }, (err) => { Toast.fail("复制失败"); } ); }); } else { Toast.fail(data.message); } }) .catch((error) => { if (error.message !== "") { Toast.fail(error.message); } }); }); };