在使用uniapp开发时需要生成二维码,用户可以进行扫码。 首先需要使用到UQRCode插件,可以参考文档,文档上写的很详细,各种方法都列出来了 UQRCode文档 我们需要做的就是将其封装成公用的组件,方便使用。
按文档安装后,直接引入,下面是完整代码
<template>
<view>
<image v-if="qrCodeUrl" :src="qrCodeUrl" :style="{ width: size+'px', height: size+'px'}"></image>
<canvas v-else canvas-id="qrcode" :style="{ width: size+'px', height: size+'px'}"></canvas>
</view>
</template>
<script>
import UQRCode from "uqrcodejs";
export default {
props: {
size: {
type: Number,
default: 100
}
},
data() {
return {
qrCodeUrl: ''
}
},
methods: {
createQRcode(url) {
// 获取uQRCode实例
var qr = new UQRCode();
// 设置二维码内容
qr.data = url;
// 设置二维码大小,必须与canvas设置的宽高一致
qr.size = this.size;
// 调用制作二维码方法
qr.make();
// 获取canvas上下文
var canvasContext = uni.createCanvasContext('qrcode', this); // 如果是组件,this必须传入
// 设置uQRCode实例的canvas上下文
qr.canvasContext = canvasContext;
// 调用绘制方法将二维码图案绘制到canvas上
qr.drawCanvas()
setTimeout(() => {
this.toImg()
}, 300)
},
toImg() {
const _this = this
uni.canvasToTempFilePath({
width: this.size,
height: this.size,
canvasId: 'qrcode',
success: function(res) {
console.log( res.tempFilePath)
_this.qrCodeUrl = res.tempFilePath
},
fail: (err) => {
console.log(err)
}
},this)
},
savePhoto() {
uni.saveImageToPhotosAlbum({
filePath: this.qrCodeUrl,
success: res => {
this.$ui.textToast('保存成功')
},
fail: err => {
this.$ui.textToast('保存失败')
}
});
}
}
}
</script>
<style lang="scss">
</style>
组件封装完成了,页面使用的话,使用refs调用组件内生成二维码的方法
<template>
<view class="qrcode">
<UQRCode ref="uqrcode" :size="175"></UQRCode>
</view>
</template>
<script>
import UQRCode from '@/components/UQRCode.vue'
import {code} from '@/api/me.js'
export default {
components: {
UQRCode
},
onLoad(){
this.getCode()
},
methods:{
getCode(){
// 发起请求,请求二维码信息
code({ rule: this.pay_method}).then(res=>{
let name=res.data.user.username
let avatar=res.data.user.avatar
let id=res.data.receiver_id
let tp=res.data.user.user_type
// 调用方法,生成二维码
// 设置需要跳转的链接,将参数带上
this.$refs.uqrcode.createQRcode('http://..线上地址.../#/page_wallet/payuser/paymoney?'
+'name='+name+'&tx='+avatar+'&id='+id+'&tp='+tp)
})
}
}
}
</script>