vue把链接转成二维码,实现手机扫码跳转到指定页面
使用 qrcodejs2实现
1.首先安装资源包
npm install --save qrcodejs2
2.在相关页面引入
import QRCode from "qrcodejs2
案例:点击弹窗出现二维码
<template>
<div>
<el-button type="text" @click="openDialog">点击打开二维码</el-button>
<el-dialog
title="查看二维码"
:visible.sync="addDialogVisible"
@close="closeDialog"
>
<div id="qrcode" ref="qrcode"></div>
</el-dialog>
</div>
</template>
<script>
import QRCode from "qrcodejs2";
export default {
data() {
return {
addDialogVisible: false,
url: "http://m.alyms.cn/F4.beZjAu",
};
},
methods: {
openDialog() {
this.addDialogVisible = true;
this.$nextTick(() => {
this.qrcode();
});
},
qrcode() {
let qrcode = new QRCode("qrcode", {
width: 200, // 设置宽度,单位像素
height: 200, // 设置高度,单位像素
text: this.url, // 设置二维码内容或跳转地址
});
},
// 关闭对话框时一定要清空二维码,否则下次打开对话框就会多一个
closeDialog() {
document.getElementById("qrcode").innerHTML = "";
},
},
};
</script>
<style>
.el-dialog {
width: 500px;
height: 500px;
text-align: center;
align-content: center;
}
#qrcode {
display: flex;
justify-content: center;
padding: 80px 0;
}
</style>
案例:不弹窗出现二维码
<template>
<div id="query">
<h1>二维码:</h1>
<div id="qrcode" ref="qrcode"></div>
</div>
</template>
<script>
import QRCode from "qrcodejs2";
export default {
methods: {
// 动态生成二维码
qrcode() {
let qrcode = new QRCode("qrcode", {
width: 200, // 设置宽度,单位像素
height: 200, // 设置高度,单位像素
text: "http://m.alyms.cn/F4.beZjAu", // 设置二维码内容或跳转地址
});
},
},
created() {
this.$nextTick(() => {
this.qrcode();
});
},
};
</script>
<style>
</style>
注意事项
在created里面调用的时候,要放在 this.$nextTick 回调函数里面调用,不然会报错误: Error in created hook: "TypeError: Cannot read property 'appendChild' of null"
- 如果报错:Cannot read property 'appendChild' of null
- 原因分析:div还没有生成,你就获取了div
- 解决办法:使用this.$nextTick()方法,在下次 DOM 更新循环结束之后执行延迟回调。