目录
第一章 前言
第二章 技术选型
第三章 源码
第四章 扩展
第一章 前言
二维码作为现代信息交互的重要载体,在地址分享、支付、身份验证等场景广泛应用。对于前端开发来说,后端给出地址或者我们自己输入地址生成二维码的这种需求在平常工作中应该是必须掌握的技能才是。小编在本文将手把手教你实现一个前端地址二维码生成器。
第二章 技术选型
qrcode.js(轻量级、无依赖):qrcode.js是一个用于生成二维码(Quick Response Code,快速响应码)的JavaScript库。它支持跨浏览器,通过HTML5 Canvas和DOM中的table标签实现二维码生成,且没有任何依赖项。该库能够将文本信息编码为二维码图像,广泛应用于网页、移动应用等场景。
第三章 源码
下载
npm install qrcode
yarn add qrcode
这是小编封装的组件,只需要传地址进来就好了。
// ===== CustomQrcode =====
import { toDataURL } from 'qrcode' // 使用qrcode插件
const props = defineProps({ // 接父组件传的地址
qrcodeUrl: {
type: String,
default: ''
}
})
const show = ref(false)
const qrcode = ref(null)
const onClose = () => {
show.value = false
}
// 展示二维码的方法
const showQrcode = () => {
show.value = true
nextTick(() => {
const options = { // 二维码配置
width: 200,
height: 200,
color: {
dark: '#000000',
light: '#ffffff'
}
}
// 创建二维码的地址
toDataURL(props.qrcodeUrl, options, (err, dataURL) => {
if (err) {
console.error(err)
return
}
qrcode.value.src = dataURL
})
})
}
defineExpose({
showQrcode
})
请用手机微信扫描二维码,用于执行后续业务办理。
.qrcode-area {
@extend %flex-center-center;
span {
font-size: 16px;
color: crimson;
}
.qrcode_main {
width: 300px;
height: 300px;
img {
width: 100%;
height: 100%;
}
}
}
.qrcode-area {
width: 600px;
}
.qrcode-area .el-dialog__body {
@extend %flex-center-center;
flex-direction: column;
}
使用
// qrcodeUrl 需要转成二维码的地址
第四章 扩展
添加输入框自行输入地址,但是地址需要校验二维码校验设计响应,实时性……