需求:项目需要根据链接实时生成二维码,当检测终端是PC时,将当前项目链接生成二维码供用户手机端使用
判断终端是否为mobile
1function isMobile () { 2 let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i); 3 return flag; 4}
链接准备
1this.$store.state.getQRCodeUrl = document.URL; 2//链接也可以用window.location.href 获取 3 if (!window.common.isMobile()) { 4 this.$router.push({path: '/QRCodepage'}); 5 return; 6 }
插件准备
QRCode.js 是一个用于生成二维码的 JavaScript 库。主要是通过获取 DOM 的标签,再通过 HTML5 Canvas 绘制而成,不依赖任何库。
下载命令 npm install qrcodejs2 --save
生成二维码
1<template> 2 <div class="QRCodePage"> 3 <div class="content"> 4 <div class="titleCen">请扫描二维码支付</div> 5 <div id='qrcode' class="qrCode"></div> 6 </div> 7 </div> 8</template> 9 10<script> 11import QRCode from 'qrcodejs2'; 12export default { 13 name: 'QRCodePage', 14 data () { 15 return { 16 url: '' 17 }; 18 }, 19 created () { 20 this.url = this.$store.state.getQRCodeUrl; 21 }, 22 mounted () { 23 this.createQRCode(); 24 }, 25 methods: { 26 createQRCode () { 27 var qrcode = new QRCode('qrcode', { 28 text: this.url, 29 width: 300, 30 height: 300, 31 colorDark: '#000000', 32 colorLight: '#ffffff', 33 correctLevel: QRCode.CorrectLevel.H 34 }); 35 qrcode.makeCode(this.url); // 生成二维码 36 } 37 } 38 39}; 40</script> 41 42<style lang='less'> 43.QRCodePage{ 44 background-color: #f7f7f7; 45 height: 100%; 46 .content{ 47 width: 300px; 48 height: 300px; 49 margin: 20px auto; 50 .titleCen{ 51 text-align:center; 52 } 53 .qrCode{ 54 width: 90%; 55 margin:20px auto; 56 } 57 } 58} 59 60</style> 61 62
###注意: 在本地调试时报错-----vue.runtime.esm.js?2b0e:1888 Error: code length overflow. (1676>1056) 发布到测试上用测试域名就好了
