最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Vue2前端生成二维码并完成扫码跳转完整教程
时间:2026-06-08 08:31:53 编辑:袖梨 来源:一聚教程网
前言
在日常开发中,我们经常会遇到这样的需求:

在页面生成一个二维码
用户用手机扫码后,自动跳转到指定网页
比如:
- 活动推广链接
- H5 页面入口
- 扫码登录
- 分享邀请页
一、实现原理
其实逻辑非常简单:
- 前端生成二维码(内容是一个 URL)
- 手机扫码 → 自动识别二维码中的 URL
- 浏览器打开该 URL
重点:二维码本质上只是“存储字符串(URL)”
二、安装依赖
推荐使用轻量好用的库:qrcode
npm install qrcode三、基础实现(Vue2)
代码示例
<template> <div> <canvas ref="qrcodeCanvas"></canvas> </div></template><script>import QRCode from "qrcode";export default { name: "QrCodeDemo", mounted() { this.generateQRCode(); }, methods: { generateQRCode() { const url = "https://www.baidu.com"; // 扫码后跳转的地址 QRCode.toCanvas( this.$refs.qrcodeCanvas, url, { width: 200, margin: 2 }, function (error) { if (error) console.error(error); console.log("二维码生成成功!"); } ); } }};</script>效果说明
页面加载后会生成一个二维码:
用户扫码后 → 自动打开 https://www.baidu.com
四、进阶用法
动态生成二维码(带参数)
const url = `https://yourdomain.com/page?id=123&type=vue`;
适用于:
- 活动分享
- 用户邀请
- 页面跳转
页面直接展示二维码图片
<template> <img :src="qrCodeUrl" /></template><script>import QRCode from "qrcode";export default { data() { return { qrCodeUrl: "" }; }, mounted() { QRCode.toDataURL("https://www.baidu.com").then(url => { this.qrCodeUrl = url; }); }};</script>五、常见问题(避坑指南)
1. URL 必须是完整路径
错误写法:
/page?id=1
正确写法:
https://yourdomain.com/page?id=1
2. localhost 无法扫码访问
如果二维码内容是:
http://localhost:8080
手机是打不开的!
解决方案:
- 使用局域网 IP(如
http://192.168.1.100:8080) - 或部署到服务器
3. 微信扫码限制
在微信中扫码时:
- 非 HTTPS 可能被拦截
- 某些域名可能被提示风险
建议统一使用 HTTPS