系列文章专栏地址:
本期内容:
- 二维码制作
一、前景介绍
我们的教师端有课程管理内容,需要添加课程,并邀请学生加入课程,这个功能如果让老师手动添加太过麻烦,所以我们打算采用二维码+暗号的方式让学生加入班级。
本次我们的重点是二维码的制作。
二、vue中引入二维码
先展示效果,打码了为了过审(忽略那些文字,中间的二维码才是关键)
总体代码:
<template>
<p style="margin:0px;padding:0px;margin-bottom:20px;">邀请学生扫描此二维码加入课程</p>
<div class="qrcode" ref="qrcodeContainer" style="width:80%;margin:10%;"></div>
<p>或输入课程暗号加入课程</p> <h3>8ZHA</h3>
</template>
<script>
import QRCode from 'qrcodejs2' // 引入qrcode
export default {
name : 'test',
mounted () {
this.$nextTick(()=> {
this.qrcode();
})
},
data(){
return{
teacher:localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
courseid:'1',
}
},
methods: {
qrcode() {
let current_url=window.location.href.slice(0,-11);
let href=current_url+'/invitation'+'?id1='+this.teacher.userid+'&id2='+this.courseid;
// window.open(href);
let qrcode = new QRCode(this.$refs.qrcodeContainer, {// eslint-disable-line no-unused-vars
width: 200,
height: 200,
text: href, // 二维码对应的地址
colorDark : "#000",
colorLight : "#fff",
correctLevel: QRCode.CorrectLevel.H
})
},
}
}
</script>
具体步骤:
-
第一步:安装qrcodejs2
我试了很多包,发现还是这个有效。在命令行输入:npm install qrcodejs2 --save -
第二步:写个页面
<template>
<p style="margin:0px;padding:0px;margin-bottom:20px;">邀请学生扫描此二维码加入课程</p>
<div class="qrcode" ref="qrcodeContainer" style="width:80%;margin:10%;"></div>
<p>或输入课程暗号加入课程</p> <h3>8ZHA</h3>
</template>
中间的这一行是关键 <div class="qrcode" ref="qrcodeContainer" style="width:80%;margin:10%;"></div>
- 第三步:写js部分,import qrcodejs2
<script>
import QRCode from 'qrcodejs2' // 引入qrcode
export default {
name : 'test',
mounted () {
this.$nextTick(()=> {
this.qrcode();
})
},
data(){
return{
teacher:localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
courseid:'1',
}
},
methods: {
qrcode() {
let current_url=window.location.href.slice(0,-11);
let href=current_url+'/invitation'+'?id1='+this.teacher.userid+'&id2='+this.courseid;
// window.open(href);
let qrcode = new QRCode(this.$refs.qrcodeContainer, {// eslint-disable-line no-unused-vars
width: 200,
height: 200,
text: href, // 二维码对应的地址
colorDark : "#000",
colorLight : "#fff",
correctLevel: QRCode.CorrectLevel.H
})
},
}
}
</script>
在qrcode()这个方法中,真正有用的是下面这一段,注意text:href
href 可以替换成比如:‘www.baidu.com’ 这样就可以访问百度了(或者’https://www.baidu.com’)
let qrcode = new QRCode(this.$refs.qrcodeContainer, {// eslint-disable-line no-unused-vars
width: 200,
height: 200,
text: href, // 二维码对应的地址
colorDark : "#000",
colorLight : "#fff",
correctLevel: QRCode.CorrectLevel.H
})
三、结果展示
我贴在博客的这个二维码是localhost,所以访问不了,不过可以用二维码阅读器查看自己的地址,经过确定确实无误。那就完成了
之后在部署的时候,地址会改成服务器地址就自然可以访问了。