|
今天来谈一下前端如何生成二维码。
对于APP应用而言,市场推广是必不可少而且是最为烧钱的阶段,那么,为满足市场推广的需求,仅仅是微信,QQ,朋友圈等连接分享的方式是不够的,当然还得包括面对面分享,那么市场人员的二维码就显得必不可少了。那又如何动态生成二维码呢,本来打算是让后端生成返回前端进行展示的,但是后端人员却完成不了,没办法只有自己去琢磨了。
对于前端生成二维码的js插件还是比较多的,刚开始找的就只是纯web端原生的js插件,但是并不符合我的项目需求,因为用的uni-app框架,不经过封装是用不了的,最终找到自己比较满意的经封装的js。
首先下载你需要下载weapp-qrcode.js(百度网盘下载链接:链接:https://pan.baidu.com/s/1VXhq3ZjxmDcH1tFujKg75Q 提取码:vj2y)
然后就直接给大家上代码吧,这是我直接封装的本地组件:
<template> <view class=""> <view class="qrcode-box" :class="modal?'show':'hide'" @tap="hideQrcode"> <view class="qrcode-item"> <view class="item-box"> <view class="title">推广码</view> <canvas class="canvas" style="width: 550rpx;height: 550rpx;" canvas-id="couponQrcode"></canvas> </view> </view> </view> </view> </template>
<script> const qrCode = require('@/common/weapp-qrcode.js') export default { data() { return { show:true } }, props:{ modal:{ type:Boolean, default:false }, url:{ type:String, default:'' } }, methods: { // 展示二维码 // showQrcode(){ // this.modal=true; // let ID=uni.getStorageSync('userInfo').id; // let url="https://www.ttlwl.cn/appDownload.html?shareUserId="+ID; // this.couponQrCode(url); // }, hideQrcode(){ // this.modal=false; this.$emit("hideQrcode") }, // 二维码生成工具 couponQrCode() { let _this=this; new qrCode('couponQrcode', { text: this.url, width: 260, height: 260, colorDark: "#333333", colorLight: "#FFFFFF", correctLevel: qrCode.CorrectLevel.H }) } }, mounted() { } </script>
<style scoped lang="scss"> .qrcode-box{ position: fixed; left: 0; top: 0; right: 0; bottom: 0; height: 100vh; width: 100vw; background-color: rgba(59,59,59,0.6); // opacity: 0.8; text-align: center; display: flex; align-items: center; display: none; .qrcode-item{ flex: 1; position: relative; text-align: center; .item-box{ width: 90%; margin: auto; display: inline-block; margin-top: 30%; padding-bottom: 30rpx; // animation: show 0.7s; .title{ font-size: 46rpx; text-align: center; margin-bottom: 24rpx; } .canvas{ margin: auto; display: inline-block; margin: auto; } background-color: #FFFFFF; } } } .opacity{ opacity: 0; display: block; } .show{ display: block; animation: fade 0.7s; // -moz-animation: fade 0.5s; /* Firefox */ // -webkit-animation: fade 0.5s; /* Safari 和 Chrome */ // -o-animation: fade 0.5s; } .hide{ animation: hide 0.7s; } @keyframes fade { from { opacity: 0.8; } to { opacity: 1; } } @keyframes hide { from {opacity: 1;} to {opacity: 0;} } </style>
然后在页面里进行引用即可:
组件引用
<qrcode ref="qrcode" :modal="modal" :url="url" @hideQrcode="hideQrcode"></qrcode>
// 展示二维码 showQrcode(){ let _this=this; this.modal=true; // uni.showLoading() setTimeout(function(){ // uni.hideLoading() _this.$refs.qrcode.couponQrCode() },50) },
//传入组件的方法 hideQrcode(){ this.modal=false; }
**********
这里一定要注意:
setTimeout(function(){ // uni.hideLoading() _this.$refs.qrcode.couponQrCode() },50)
因为刚开始元素:display:none,此时,调用二维码生成方法,是生成不了的,所以得用setTimeout延后执行,这样显隐切换才会正常。
来源:https://www.cnblogs.com/chenjianbao/p/13594687.html |