安装
pnpm add qrcode
pnpm add @types/qrcode -D
版本: 1.5.1
编写帮助方法
import QRCode, { QRCodeRenderersOptions } from 'qrcode'
/**
* 将二维码存为png并Download下载
*
* @param filename 文件名(无需带后缀)
* @param picBase64Url 二维码的base64串
*/
function savePicAndDownload(fileName: string, picBase64Url: string) {
const a = document.createElement('a')
a.href = picBase64Url
a.download = `${fileName}.png`
a.click()
}
/**
* 下载download png二维码的方法
*
* @param {string} fileName [fileName description]
*
* @return {[type]} [return description]
*/
export type QRCodePicDownloadMethod = (fileName: string) => void
/**
* 生成二维码并返回导出为png的方法
*
* @param content 二维码内容
* @param divEle 承载二维码的div元素
* @param options 二维码配置信息
*
* @return {[HTMLCanvasElement]} 导出为png的方法
*/
export function buildQRCode(
content: string,
divEle: HTMLDivElement,
options: QRCodeRenderersOptions
): Promise<QRCodePicDownloadMethod> {
divEle.innerHTML = ''
const canvas = document.createElement('canvas')
divEle.appendChild(canvas)
return new Promise<QRCodePicDownloadMethod>(reslove => {
QRCode.toDataURL(canvas, content, options).then(picBase64Url => {
reslove((filename: string) => savePicAndDownload(filename, picBase64Url))
})
})
}
调用示例
import { buildQRCode, QRCodePicDownloadMethod } from '@/utils/qrcodeUtil'
import { onMounted, ref } from 'vue'
const divRef = ref<HTMLDivElement>()
let qrcodeDownloadMethod: QRCodePicDownloadMethod
async function qrcodeFactory(url: string) {
qrcodeDownloadMethod = await buildQRCode(url, divRef.value as HTMLDivElement, {
color: {
// 二维码颜色
dark: '#000000',
// 二维码背景色
light: '#ffd8bf',
},
// 二维码留白边距(默认:4)
margin: 4,
// 二维码宽/高(这个宽高已经将留白包含在内)
width: 200,
// 二维码容错级别
errorCorrectionLevel: 'H',
})
}
onMounted(() => {
qrcodeFactory('http://192.169.200.1')
})
function onRebuild() {
qrcodeFactory(`http://192.169.200.1?_t=${new Date().getTime()}`)
}
function onDownload() {
if (qrcodeDownloadMethod) {
qrcodeDownloadMethod('二维码')
}
}