qrcode-reader内容参考:https://blog.csdn.net/qq_37816525/article/details/100532716
功能实现了:
一行是text文本框,输入内容在框失去焦点时要在下面图片显示区域生成二维码。另一行显示二维码图片,在文本中没有数据时要显示提交图片按钮,上传二维码识别内容后显示二维码,并把值赋值给上面的文本框,隐藏提交按钮。
HTML代码:
<el-form-item label="二维码内容">
<el-input v-model="codeContent" @blur="createQRcode"></el-input>
</el-form-item>
<el-form-item label="二维码图片">
<img v-if="codeContent" id="qrcodeImg"></img>
<!-- 转换后图片显示位置 -->
<div class="image-box">
<input v-if="!codeContent" accept="image/*" id="file" type="file" @change="handleImageUpload" />
</div>
<!-- 没有图片时或图片不正确时显示上传按钮 -->
</el-form-item>
JS代码:
import QRCode from "qrcode";
import QrcodeDecoder from "qrcode-decoder";
export defalut {
data(){
return {
codeContent: "",
codeImage: ""
}
},
methods: {
//生成二维码
createQRcode(){
let qrcodeDom = document.getElementById("qrcodeImg");
if (this.codeContent) {
QRCode.toDataURL(this.codeContent).then(url => {
qrcodeDom.setAttribute("src", url);
})
.catch(err => {
console.error(err);
})
}
},
// 处理导入的图片
async handleImageUpload(file){
let imgUpload = document.getElementById("file");
if (imgUpload.files[0].type.indexOf("image/")>=0) {
let qr = new QrcodeDecoder();
let res = await qr.decodeFromImage(this.getObjectURL(imgUpload.files[0]));
if(res){
let reader = new FileReader();
reader.readAsDataURL(imgUpload.files[0]);
if(res.data !== ''){
reader.onload = function(e) {
let url = this.result.substring(this.result.indexOf(",") + 1);
let qrcodeDom = document.getElementById("qrcodeImg");
qrcodeDom.setAttribute("src", "data:image/png;base64," + url);
};
this.codeContent = res.data;
}
}else{
imgUpload.value = "";
this.$message.error('二维码格式错误,请重新上传');
}
} else {
this.$message.error('请上传图片');
}
},
getObjectURL(file) {
var url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}
}
}