uniapp二维码生成
参考文档
【博主:ChoneyLove】uniapp中生成二维码及解决微信小程序端问题总结
依赖引入
shell
npm i uqrcodejs
代码
html部分
html
<canvas type="2d" id="qrCode" canvas-id="qrCode" style="width: 72rpx; height: 72rpx;"></canvas>
生成代码(vue3 hook)
javascript
// 生成二维码
import UQRCode from 'uqrcodejs';
import { onShow } from "@dcloudio/uni-app"
import { nextTick } from 'vue';
export default function useCreateQRCode(type : number = 0, targetName : string = 'qrCode', size : number = 72) {
// 生成二维码
const createQRCode = async () => {
let url = `...`;
console.log(url);
let qr = new UQRCode();
qr.data = url
qr.size = uni.upx2px(size); // 注意这里大小要跟画布大小一致,否则二维码可能超出画布
qr.make();
const canvasContext = uni.createCanvasContext(targetName);
qr.canvasContext = canvasContext;
qr.drawCanvas();
}
onShow(() => {
nextTick(() => {
createQRCode();
})
})
return {}
}
使用
html
<template>
<view>
<!-- ... -->
<canvas type="2d" id="qrCode" canvas-id="qrCode" style="width: 72rpx; height: 72rpx;"></canvas>
</view>
</template>
<script setup lang="ts">
import useCreateQRCode from "@/hooks/createQRCode";
useCreateQRCode();
</script>