小工具知识网

当前位置: 首页 > 行业知识 > uniapp 生成二维码(可设置logo、前景色、背景色等),扫描二维码(uni.scanCode、barcode自定义扫码可连续扫码),Android\ios可用

行业知识

uniapp 生成二维码(可设置logo、前景色、背景色等),扫描二维码(uni.scanCode、barcode自定义扫码可连续扫码),Android\ios可用

2026-11-10 15:53:26 来源:互联网转载

一、生成二维码

如下样式

组件:

 
import tkiQrcode from './tki-qrcode.vue'export default {components: {tkiQrcode,},        data() {return {val: '', // 要生成的二维码值,一变就自动刷新二维码size: 400, // 二维码大小unit: 'upx', // 单位// background: '#4568E8', // 背景色foreground: '#61AF52', // 前景色// pdground: '#32dbc6', // 角标色icon: '../../../../static/img/icon/1024.png', // 二维码图标iconsize: 40, // 二维码图标大小lv: 3, // 二维码容错级别 , 一般不用设置,默认就行onval: false, // val值变化时自动重新生成二维码loadMake: true, // 组件加载完成后自动生成二维码src: '' ,// 二维码生成后的图片地址或base64};},},

tki-qrcode.vue

import QRCode from "./qrcode.js"let qrcodeexport default {name: "tki-qrcode",props: {cid: {type: String,default: 'tki-qrcode-canvas'},size: {type: Number,default: 200},unit: {type: String,default: 'upx'},show: {type: Boolean,default: true},val: {type: String,default: ''},background: {type: String,default: '#ffffff'},foreground: {type: String,default: '#000000'},pdground: {type: String,default: '#000000'},icon: {type: String,default: ''},iconSize: {type: Number,default: 40},lv: {type: Number,default: 3},onval: {type: Boolean,default: false},loadMake: {type: Boolean,default: false},usingComponents: {type: Boolean,default: true},showLoading: {type: Boolean,default: true},loadingText: {type: String,default: '二维码刷新...'},},data() {return {result: '',}},methods: {_makeCode() {let that = thisif (!this._empty(this.val)) {qrcode = new QRCode({context: that, // 上下文环境canvasId:that.cid, // canvas-idusingComponents: that.usingComponents, // 是否是自定义组件showLoading: that.showLoading, // 是否显示loadingloadingText: that.loadingText, // loading文字text: that.val, // 生成内容size: that.cpSize, // 二维码大小background: that.background, // 背景色foreground: that.foreground, // 前景色pdground: that.pdground, // 定位角点颜色correctLevel: that.lv, // 容错级别image: that.icon, // 二维码图标imageSize: that.iconSize,// 二维码图标大小cbResult: function (res) { // 生成二维码的回调that._result(res)},});} else {uni.showToast({title: '二维码内容不能为空',icon: 'none',duration: 2000});}},_clearCode() {this._result('')qrcode.clear()},_saveCode() {let that = this;if (this.result != "") {uni.saveImageToPhotosAlbum({filePath: that.result,success: function () {uni.showToast({title: '二维码保存成功',icon: 'success',duration: 2000});}});}},_result(res) {this.result = res;this.$emit('result', res)},_empty(v) {let tp = typeof v,rt = false;if (tp == "number" && String(v) == "") {rt = true} else if (tp == "undefined") {rt = true} else if (tp == "object") {if (JSON.stringify(v) == "{}" || JSON.stringify(v) == "[]" || v == null) rt = true} else if (tp == "string") {if (v == "" || v == "undefined" || v == "null" || v == "{}" || v == "[]") rt = true} else if (tp == "function") {rt = false}return rt}},watch: {size: function (n, o) {if (n != o && !this._empty(n)) {this.cSize = nif (!this._empty(this.val)) {setTimeout(() => {this._makeCode()}, 100);}}},val: function (n, o) {if (this.onval) {if (n != o && !this._empty(n)) {setTimeout(() => {this._makeCode()}, 0);}}}},computed: {cpSize() {if(this.unit == "upx"){return uni.upx2px(this.size)}else{return this.size}}},mounted: function () {if (this.loadMake) {if (!this._empty(this.val)) {setTimeout(() => {this._makeCode()}, 0);}}},}.tki-qrcode {  position: relative;}.tki-qrcode-canvas {  position: fixed;  top: -99999upx;  left: -99999upx;  z-index: -99999;}

使用:

this.$refs.qrcode._makeCode()

二、扫描二维码

扫描需要的配置

 manifest.json

"app-plus" : {        "modules" : {            "Barcode" : {},            "Camera" : {},            "Push" : {}        },   },

Android相机权限判断

先判断当前是Android还是ios

var _this = thisuni.getSystemInfo({success: function(e) {_this.deviceType = e.platform}})let device = this.deviceType.toLowerCase() == ('ios' || 'macos') ? 'ios' : 'android'console.log(device)

Android端需要权限判断

if (device == 'android') {plus.android.requestPermissions(['android.permission.CAMERA'],function(e) {console.log('android.permission.CAMERA',e)if (e.deniedAlways.length > 0) { //权限被永久拒绝// 弹出提示框解释为何需要读写手机储存权限,引导用户打开设置页面开启console.log('Always Denied!!! ' + e.deniedAlways.toString());uni.showModal({title: '提示',content: '请打开手机相机功能(点击确定后在权限中授权相机功能)',// showCancel: false, // 不显示取消按钮success(res) {if (res.confirm) {var Intent = plus.android.importClass("android.content.Intent");var Settings = plus.android.importClass("android.provider.Settings");var Uri = plus.android.importClass("android.net.Uri");var mainActivity = plus.android.runtimeMainActivity();var intent = new Intent();intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);var uri = Uri.fromParts("package", mainActivity.getPackageName(),null);intent.setData(uri);mainActivity.startActivity(intent);}}});}if (e.deniedPresent.length > 0) { //权限被临时拒绝// 弹出提示框解释为何需要读写手机储存权限,可再次调用plus.android.requestPermissions申请权限plus.android.requestPermissions(['android.permission.CAMERA'])console.log('Present Denied!!! ' + e.deniedPresent.toString());}if (e.granted.length > 0) { //权限被允许//调用依赖获取读写手机储存权限的代码console.log('Granted!!! ' + e.granted.toString());_this.scanQRCode() // 获取权限成功之后调用的函数}},function(e) {console.log('Request Permissions error:' + JSON.stringify(e));});}else {_this.scanQRCode() // 获取权限成功之后调用的函数}

先判断当前有没有网络

var that = thisuni.getNetworkType({    success: function (res) {        const networkType = res.networkType;console.log('networkType',networkType)        if (networkType === 'none') {        uni.vibrateLong({        success: function () {        console.log('success');        }        });innerAudioContext.src = '../../../../static/wuwangl.MP3';innerAudioContext.play();innerAudioContext.onEnded(function(res) {console.log('innerAudioContext.onEnded')innerAudioContext.destroy() //先销毁音频innerAudioContext = null // 再赋值为nullinnerAudioContext = uni.createInnerAudioContext() // 最后再创建一个新的})        }     }});

执行扫码操作

uni.scanCode({onlyFromCamera: true,autoZoom:false,// hideAlbum:true,    success(res) {console.log('scanCode',res)        if (res.result) {            console.log('扫描结果:', res.result);that.qrcodePram.qrcode_data = res.resultthat.set_user_qrcode()        } else {this.$refs.toast.show('扫描失败',2);        }    },    fail() {        // uni.showToast({        //     title: '调用相机失败',        //     icon: 'none'        // });    }});

扫码准确度较低的解决办法

uni.scanCode({scanType:['barCode'],success: function (res) {console.log('条码类型:' + res.scanType);console.log('条码内容:' + res.result);}});

1、使用中发现存在准确率较低的问题,可以根据需求通过限制ScanType的类型来提高准确率。

2、如果对准确度有更高的要求,则可以使用支付宝插件。

扫码成功后语音提示

let innerAudioContext = uni.createInnerAudioContext();innerAudioContext = uni.createInnerAudioContext() // 最后再创建一个新的innerAudioContext.src = '../../../../static/ok.MP3';innerAudioContext.play();

使用barcode自定义扫码,可连续扫码

   export default {  data() {    return {      nfcFlag: false,      barcode: null,      lightIsShow: false, //是否打开摄像头    };  },  onLoad() {    this.nfcFlag = uni.getStorageSync("isNFCFlag");    let currentWebview = this.$scope.$getAppWebview();    this.createBarcode(currentWebview); //开启扫码    this.createView(currentWebview); // 创建打开手电筒  },  onHide() {    //页面隐藏时手电筒打开关闭    if (this.lightIsShow) {      this.lightIsShow = false;      this.barcode.setFlash(false);    }  },  onShow() {    var that = this;    // 页面展示时,重新启动扫描检测    if (this.barcode) {      setTimeout(function () {        let currentWebview = that.$scope.$getAppWebview();        that.createBarcode(currentWebview); //开启扫码        that.createView(currentWebview); // 创建打开手电筒      }, 300);    }  },  methods: {    //从跳转后的页面返回    navigationTap() {      this.barcode = null;      let currentWebview = this.$scope.$getAppWebview();      this.createBarcode(currentWebview); //开启扫码      this.createView(currentWebview); // 创建打开手电筒    },    // 扫描二维码    createBarcode(currentWebview) {      if (!this.barcode) {        this.barcode = plus.barcode.create("barcode", [plus.barcode.QR], {          top: `0px`,          left: "0px",          height: `100%`,          width: "100%",          position: "absolute",          background: "#000000",          frameColor: "#008EFF",          scanbarColor: "#008EFF",        });        this.barcode.onmarked = this.onmarked; //成功回调        this.barcode.onerror = this.onerror; //失败回调        currentWebview.append(this.barcode);      }      this.barcode.start();    },    // 创建打开手电筒    createView(currentWebview) {      var scanBarVew = new plus.nativeObj.View(        "scanBarVew",        {          top: "60%",          left: "40%",          height: "10%",          width: "20%",        },        [          //图片          {          tag: 'img',          id: 'scanBar',          src: 'static/scanBar.png',//图片路径自选          position: {          width: '28%',          left: '36%',          height: '30%'          }          },          //文字          {            tag: "font",            id: "font",            text: "轻触照亮",            textStyles: {              size: "10px",              color: "#ffffff",            },            position: {              width: "80%",              left: "10%",            },          },        ]      );      scanBarVew.interceptTouchEvent(true);      currentWebview.append(scanBarVew);      //点击事件      var that = this;      scanBarVew.addEventListener(        "click",        function (e) {          that.lightIsShow = !that.lightIsShow;          if (that.lightIsShow) {            scanBarVew.draw([              {                tag: "font",                id: "font",                text: "轻触照亮",                textStyles: {                  size: "10px",                  color: "#ffffff",                },                position: {                  width: "80%",                  left: "10%",                },              },            ]);          } else {            scanBarVew.draw([              {                tag: "font",                id: "font",                text: "轻触照亮",                textStyles: {                  size: "10px",                  color: "#ffffff",                },                position: {                  width: "80%",                  left: "10%",                },              },            ]);          }          if (that.barcode) {            that.barcode.setFlash(that.lightIsShow);          }        },        false      );    },    // 扫码成功回调    onmarked(type, result) {      this.barcode.cancel();      var that = this;      console.log(result);      // type==0 意味着扫码成功(二维码,如要扫描其它需自行判定)      if (type == 0) {      } else {        uni.showToast({          title: `请扫描二维码`,          duration: 2000,          icon: "none",        });        let that = this;        setTimeout(function () {          that.barcode.start();        }, 2000);      }    },    // 失败回调    onerror(type, result) {      console.log(result);    },  },};.scan-container {width: 750rpx;background-color: rgba(245, 245, 245, 1);}.basic-information {margin-top: 30rpx;width: 690rpx;margin-left: 30rpx;background-color: rgba(255, 255, 255, 1);border-radius: 10px;}.basic-information-content {width: 630rpx;margin-left: 30rpx;}.basic-information-title {height: 46rpx;flex-wrap: wrap;flex-direction: row;align-items: center;margin-top: 40rpx;margin-bottom: 40rpx;}.information-title-stick {width: 8rpx;height: 32rpx;background-color: rgba(0, 141, 235, 1);margin-right: 20rpx;}.information-title-text {width: 128rpx;line-height: 46rpx;font-size: 32rpx;font-weight: 500;color: rgba(51, 51, 51, 1);}.basic-information-personal {margin-bottom: 40rpx;flex-wrap: wrap;height: 250rpx;}.information-personal-img {width: 188rpx;height: 250rpx;margin-right: 40rpx;}.information-personal-name {width: 402rpx;flex-wrap: wrap;flex-direction: row;}.information-personal-name1 {width: 200rpx;height: 250rpx;justify-content: space-between;}.information-personal-name1a {height: 40rpx;line-height: 40rpx;font-size: 28rpx;color: rgba(51, 51, 51, 1);}.information-personal-name2 {width: 202rpx;justify-content: space-between;}.information-personal-name2a {height: 40rpx;line-height: 40rpx;font-size: 28rpx;color: rgba(102, 102, 102, 1);text-align: right;}.basic-information-identity {margin-bottom: 40rpx;flex-wrap: wrap;flex-direction: row;}.information-identity-title {width: 140rpx;line-height: 40rpx;color: rgba(51, 51, 51, 1);font-size: 28rpx;text-align: left;margin-right: 40rpx;}.information-identity-content {width: 450rpx;line-height: 40rpx;font-size: 28rpx;color: rgba(102, 102, 102, 1);text-align: right;}.work-information {margin-top: 20rpx;width: 690rpx;margin-left: 30rpx;background-color: rgba(255, 255, 255, 1);border-radius: 10rpx;}.work-information-content {width: 630rpx;margin-left: 30rpx;}.company-profile {margin-top: 40rpx;height: 40rpx;flex-wrap: wrap;flex-direction: row;align-items: center;justify-content: center;}.company-profile-number {width: 109rpx;line-height: 34rpx;color: rgba(153, 153, 153, 1);font-size: 24rpx;}.company-profile-c {border-radius: 50rpx;color: rgba(153, 153, 153, 1);font-size: 24rpx;line-height: 20rpx;width: 28rpx;height: 28rpx;border-style: solid;border-width: 2rpx;border-color: rgba(153, 153, 153, 1);text-align: center;margin-right: 1rpx;}.company-profile-name {color: rgba(153, 153, 153, 1);font-size: 24rpx;width: 384rpx;line-height: 34rpx;}.worker-information-title {width: 210rpx;}.worker-information-content {width: 380rpx;}.work-information1 {margin-bottom: 30rpx;}

   uniapp32套精选源码截图:

​

关注公众号「码农园区」,回复 【uniapp源码】,即可获取全套源码下载链接

上一篇:马桶是怎么创服务器的?

下一篇:Upload 上传(图片/文件),回显(图片),下载(文件)