Vue3+TypeScript實現(xiàn)二維碼生成組件
簡介
在 Web 應(yīng)用中,生成二維碼是常見的需求。本文介紹如何用 Vue3 和 TypeScript 開發(fā)一個二維碼生成組件,支持生成圖片或 canvas 形式的二維碼,并提供豐富的配置選項。
技術(shù)棧
- Vue3
- TypeScript
- Element Plus
- qrcode
- 圖片預(yù)覽組件
組件功能
- 支持生成圖片和 canvas 形式的二維碼: 可以根據(jù)需求選擇生成圖片或 canvas 形式的二維碼。
- 自定義配置選項: 提供豐富的配置選項,如二維碼大小、圖標大小、二維碼顏色、容錯級別等。
- 支持lgog二維碼: canvas 形式下支持配置logo二維碼。
- 二維碼預(yù)覽: 圖片形式下支持二維碼預(yù)覽功能。
- 下載: 組件內(nèi)提供下載二維碼到本地的方法。
組件代碼
生成uuid
方法,防止在 canvas 形式下同一頁面生成多個二維碼時導致 canvasId
重復(fù)
/** * @description 生成唯一 uuid * @return string */ export function generateUUID() { if (typeof crypto === "object") { if (typeof crypto.randomUUID === "function") { return crypto.randomUUID(); } if (typeof crypto.getRandomValues === "function" && typeof Uint8Array === "function") { const callback = (c: any) => { const num = Number(c); return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(16); }; return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, callback); } } let timestamp = new Date().getTime(); let performanceNow = (typeof performance !== "undefined" && performance.now && performance.now() * 1000) || 0; return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => { let random = Math.random() * 16; if (timestamp > 0) { random = (timestamp + random) % 16 | 0; timestamp = Math.floor(timestamp / 16); } else { random = (performanceNow + random) % 16 | 0; performanceNow = Math.floor(performanceNow / 16); } return (c === "x" ? random : (random & 0x3) | 0x8).toString(16); }); }
以下是組件的核心代碼:
<script setup lang="ts"> import { ref, onMounted, computed } from "vue"; import QRCode, { type QRCodeRenderersOptions } from "qrcode"; import { generateUUID } from "@/utils/util"; interface QRCodeProps { type?: "canvas" | "img"; // 二維碼類型 ==> 默認img, img 支持預(yù)覽,canvas支持logo size?: number; // 二維碼大小 ==> 默認200 iconSize?: number; // 二維碼圖標大小 ==> 默認40 content: string; // 二維碼內(nèi)容 ==> 必填 logo?: string; // 二維碼logo ==> 默認無 options?: QRCodeRenderersOptions; // 二維碼配置 ==> 默認無 errorLevel?: "L" | "M" | "Q" | "H"; // 二維碼容錯級別 ==> 默認H } // 接收父組件參數(shù)并設(shè)置默認值 const props = withDefaults(defineProps<QRCodeProps>(), { type: "img", size: 200, iconSize: 40, errorLevel: "H" }); const qrCodeUrl = ref<string>(""); const canvasId = ref("canvas" + generateUUID()); const loading = ref(true); const QRCodeStyle = computed(() => { return { width: props.size + "px", height: props.size + "px" }; }); // 生成二維碼 const initQRCode = async () => { if (props.type === "canvas") { const canvasRef: any = await QRCode.toCanvas(document.getElementById(canvasId.value), props.content, { width: props.size, margin: 2, errorCorrectionLevel: props.errorLevel, ...props.options }); if (props.logo) { const ctx = canvasRef.getContext("2d"); const iconBgW = props.iconSize + 5; const iconBgH = props.iconSize + 5; const iconBgX = (canvasRef.width - iconBgW) / 2; const iconBgY = (canvasRef.width - iconBgH) / 2; ctx.fillStyle = "#fff"; ctx.fillRect(iconBgX, iconBgY, iconBgW, iconBgH); // logo const iconX = (canvasRef.width - props.iconSize) / 2; const iconY = (canvasRef.width - props.iconSize) / 2; const image = new Image(); image.crossOrigin = "Anonymous"; // 設(shè)置圖片的跨域?qū)傩? image.onload = () => { ctx.drawImage(image, iconX, iconY, props.iconSize, props.iconSize); qrCodeUrl.value = canvasRef.toDataURL(); }; image.src = props.logo; } else { qrCodeUrl.value = canvasRef.toDataURL(); } loading.value = false; } else { const url = await QRCode.toDataURL(props.content, { width: props.size, margin: 2, errorCorrectionLevel: props.errorLevel, ...props.options }); qrCodeUrl.value = url; loading.value = false; } }; // 下載二維碼 const downLoadQRCode = (fileName: string = generateUUID(), fileType: string = ".png") => { const exportFile = document.createElement("a"); exportFile.style.display = "none"; exportFile.download = `${fileName}${fileType}`; exportFile.href = qrCodeUrl.value; document.body.appendChild(exportFile); exportFile.click(); // 去除下載對 url 的影響 document.body.removeChild(exportFile); }; onMounted(() => { initQRCode(); }); defineExpose({ downLoadQRCode }); </script> <template> <div :style="QRCodeStyle" overflow-hidden rounded-lg border border-slate-300 border-solid v-loading="loading"> <ImagePreview :width="QRCodeStyle.width" :height="QRCodeStyle.height" v-if="type === 'img'" :image-url="qrCodeUrl" /> <canvas v-else :style="QRCodeStyle" :id="canvasId"></canvas> </div> </template> <style lang="scss" scoped></style>
總結(jié)
通過結(jié)合 Vue3、TypeScript 和其他現(xiàn)代前端技術(shù),我們打造了一個功能豐富的二維碼生成組件。該組件支持多種形式展示,包括圖片和 canvas 二維碼。用戶可以輕松放大預(yù)覽圖片二維碼,或者通過 canvas 添加自定義 logo。除此之外,在組件內(nèi)還提供了便捷的下載功能。這一解決方案為開發(fā)者在 Web 應(yīng)用中集成二維碼生成功能提供了便捷而強大的工具。
希望這篇文章能夠幫助你更好地了解如何使用 Vue3 和 TypeScript 實現(xiàn) 生成二維碼功能!如果你有任何問題或建議,請隨時提出。
以上就是Vue3+TypeScript實現(xiàn)二維碼生成組件的詳細內(nèi)容,更多關(guān)于Vue3+TypeScript二維碼的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue中$nexttick,$set,$forceupdate的區(qū)別
本文主要介紹了vue中$nexttick,$set,$forceupdate的區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07Vue2實現(xiàn)圖片的拖拽,縮放和旋轉(zhuǎn)效果的示例代碼
這篇文章主要為大家介紹了如何基于vue2?實現(xiàn)圖片的拖拽、旋轉(zhuǎn)、鼠標滾動放大縮小等功能。文中的示例代碼講解詳細,感興趣的小伙伴可以嘗試一下2022-11-11vue實現(xiàn)動態(tài)路由的方法及路由原理解析
這篇文章主要介紹了路由原理及vue實現(xiàn)動態(tài)路由,Vue Router 提供了豐富的 API,可以輕松地實現(xiàn)路由功能,并支持路由參數(shù)、查詢參數(shù)、命名路由、嵌套路由等功能,可以滿足不同應(yīng)用程序的需求,需要的朋友可以參考下2023-06-06詳解vuex中mapState,mapGetters,mapMutations,mapActions的作用
這篇文章主要介紹了vuex中mapState,mapGetters,mapMutations,mapActions的作用,需要的朋友可以參考下2018-04-04