| | |
| | | <template> |
| | | <view class="c-qr-code"> |
| | | <canvas ref="canvas"></canvas> |
| | | <AtButton |
| | | v-if="downloadable" |
| | | type="primary" |
| | | full |
| | | :onClick="evt => handleSaveToAlbum()" |
| | | >保存到手机</AtButton> |
| | | </view> |
| | | </template> |
| | | |
| | | <script> |
| | | import Taro from '@tarojs/taro'; |
| | | import { $ } from '@tarojs/extend'; |
| | | import { AtButton } from 'taro-ui-vue'; |
| | | import QRCode from 'qrcode'; |
| | | import './cQrCode.scss'; |
| | | |
| | | export default { |
| | | name: 'CQRCode', |
| | | components: {}, |
| | | components: { |
| | | AtButton, |
| | | }, |
| | | props: { |
| | | content: { |
| | | type: String, |
| | |
| | | type: Number, |
| | | default: 2, |
| | | }, |
| | | // 是否显示保存到手机 |
| | | downloadable: { |
| | | type: Boolean, |
| | | default: false, |
| | | }, |
| | | }, |
| | | data() { |
| | | return { |
| | |
| | | }; |
| | | }, |
| | | methods: { |
| | | _renderQRCode(canvasDom) { |
| | | handleSaveToAlbum() { |
| | | if (process.env.TARO_ENV === 'h5') { |
| | | const canvasBox = $(this.$refs.canvas.$el); |
| | | const canvasDom = canvasBox.find('canvas')[0]; |
| | | const dataURL = canvasDom.toDataURL('image/png', 1); |
| | | const a = document.createElement('a'); |
| | | a.download = 'qrcode.png'; |
| | | a.href = dataURL; |
| | | a.dispatchEvent(new MouseEvent('click')); |
| | | } else { |
| | | // TODO: 小程序中下载 |
| | | } |
| | | }, |
| | | _renderQRCodeH5(canvasDom) { |
| | | QRCode.toCanvas( |
| | | canvasDom, |
| | | this.content, |
| | | { |
| | | width: this.size, |
| | | width: this.size * 2, |
| | | margin: this.margin, |
| | | }, |
| | | err => { |
| | |
| | | console.error(err); |
| | | return; |
| | | } |
| | | } |
| | | }, |
| | | ); |
| | | }, |
| | | }, |
| | | mounted() { |
| | | if (process.env.TARO_ENV === 'h5') { |
| | | const canvasBox = $(this.$refs.canvas.$el); |
| | | const finderTimer = setInterval(() => { |
| | | this.finderTimer = setInterval(() => { |
| | | const canvasDom = canvasBox.find('canvas'); |
| | | if (canvasDom.length === 0) { |
| | | return; |
| | |
| | | if (this.lastContent === this.content) { |
| | | return; |
| | | } |
| | | this._renderQRCode(canvasDom[0]); |
| | | this._renderQRCodeH5(canvasDom[0]); |
| | | this.lastContent = this.content; |
| | | }, 10); |
| | | }, 100); |
| | | } else { |
| | | // TODO: 小程序中获取canvas |
| | | } |
| | | }, |
| | | beforeDestroy() { |
| | | clearInterval(this.finderTimer); |
| | | }, |
| | | }; |
| | | </script> |