1. Install and install the qrcode library
npm install qrcode -S
Two, the specific code
I use vite+3.0+ts
and need to generate QR codes in many places, so I package it into a hook
qrcode.ts
import {
onMounted, ref } from 'vue'
import {
toDataURL } from 'qrcode'
export default function getQrcode (url: string) {
const qrCodeData = ref('')
const options = {
width: 100, // 二维码的宽度
height: 100, // 二维码的高度
color: {
dark: '#000000',
light: '#ffffff'
}
}
onMounted(() => {
toDataURL(url, options, (err, dataURL) => {
if (err) {
console.error(err)
return
}
// 在这里可以使用生成的二维码 dataURL
// console.log(dataURL)
qrCodeData.value = dataURL
})
})
return {
qrCodeData
}
}
index.view
<template>
<div class="login">
login page
<img :src="qrCodeData" alt="QR Code" title="QR Code" />
</div>
</template>
<script lang="ts" setup>
import getQrcode from '@/hooks/qrcode'
const url = 'https://blog.csdn.net/weixin_44582045' // 你想生成二维码的链接
const {
qrCodeData } = getQrcode(url)
</script>
<style lang="less" scoped>
</style>