1.生成二维码
1)安装qrcode
npm install qrcode
2)生成二维码代码
<template><el-input v-model="formData.designation"></el-input><el-input v-model="formData.people"></el-input><el-button type="primary" @click="generateQRCode">生成二维码</el-button><!-- 二维码展示 --><canvas ref="qrcodeCanvas"></canvas>
</template>
<script setup>import QRCode from 'qrcode';const formData = ref({designation:'',people:'',})const QRCodeType = ref(0)// 生成二维码const generateQRCode = async () => {try {// 获取 canvas 元素的引用const canvas = document.querySelector('canvas');// 将输入字段合并成一个字符串let data = generateString(formData.value);console.log(data)// 使用 qrcode 库生成二维码await QRCode.toCanvas(canvas, data || '', { errorCorrectionLevel: 'H' });QRCodeType.value = 1}catch (error) {console.error('Error generating QR code:', error);}// 对象合成字符串的方法const generateString = (formData) => {let result = ''for (const key in formData) {if (formData.hasOwnProperty(key)) {result += formData[key] + ','}}// 去掉末尾的逗号result = result.slice(0, -1)return result}
};
</script>
2.解析二维码
1)安装 jsqr
npm install jsqr
2)解析二维码代码
父组件
<template><parseQRCode @get-code-data="getCodeData"></parseQRCode>
</template>
<script setup>
import parseQRCode from './components/parseQRCode.vue'
// 获取得到的二维码数据
const getCodeData = (vm) =>{const codeData = vm.split(',');console.log(codeData,'获取得到的二维码数据',vm)formData.value.designation = codeData[0]formData.value.people = codeData[1]
}
</script>
子组件
<template><div><div @click="openFileInput" style="cursor: pointer;">从图像二维码导入</div><input id="fileInput" type="file" accept="image/*" style="display: none;" @change="handleFileChange"><!-- <div v-if="decodedValue">解析结果: {{ decodedValue }}</div><div v-else>未找到二维码</div> --></div>
</template><script setup>
import { ref } from 'vue';
import jsQR from 'jsqr';const decodedValue = ref(null);const emits = defineEmits(['get-code-data',
])
const openFileInput = () => {const fileInput = document.getElementById('fileInput');if (fileInput) {fileInput.click();}
};const handleFileChange = (event) => {const file = event.target.files[0];if (!file) return;const reader = new FileReader();reader.onload = (event) => {const image = new Image();image.onload = () => {const canvas = document.createElement('canvas');const context = canvas.getContext('2d');canvas.width = image.width;canvas.height = image.height;context.drawImage(image, 0, 0);const imageData = context.getImageData(0, 0, image.width, image.height);const code = jsQR(imageData.data, image.width, image.height);if (code) {decodedValue.value = code.data;emits('get-code-data', code.data);} else {decodedValue.value = null;}};image.src = event.target.result;};reader.readAsDataURL(file);
};
</script>