使用Qrcode.vue组件来生成二维码。这是一个Vue.js组件,可以轻松地在您的Vue.js应用程序中使用
安装
安装qrcodejs2:npm install qrcodejs2 --save
使用
- 创建Qrcode.vue组件:
<template>
<div id="qrcode" ref="qrcode"></div>
</template>
<script>
import QRCode from 'qrcodejs2'; //引用Qrcodejs2组件库
export default {
props: {
value: {
type: String,
required: true
},
width: {
type: Number,
default: 200
},
height: {
type: Number,
default: 200
},
colorDark: {
type: String,
default: '#000000'
},
colorLight: {
type: String,
default: '#ffffff'
}
},
watch:{
value(val){
// 清除生成的二维码(因为点击多次会生成多个二维码)
const codeHtml = document.getElementById("qrcode");
codeHtml.innerHTML = "";
const qrcode = new QRCode(this.$refs.qrcode, {
text: this.value,
width: this.width,
height: this.height,
colorDark: this.colorDark,
colorLight: this.colorLight,
correctLevel: QRCode.CorrectLevel.H
});
}
},
/* 用 watch 和 mounted 都可以(交换使用) */
// mounted() {
// const qrcode = new QRCode(this.$refs.qrcode, {
// text: this.value,
// width: this.width,
// height: this.height,
// colorDark: this.colorDark,
// colorLight: this.colorLight,
// correctLevel: QRCode.CorrectLevel.H
// });
// }
};
</script>
- 使用Qrcode.vue组件
<template>
<div>
<Button type="primary" @click="generateQRCode">出缺</Button>
</div>
<Modal
v-model="dimensional"
title="二维码"
width="20%">
<div style="display: flex;justify-content: center;align-items: center;">
<!-- 使用Qrcode组件 -->
<!-- 可以放在模态框里以及使用的地方 -->
<Qrcode :value="codeUrl" />
</div>
</Modal>
</template>
<script>
import Qrcode from '@/components/Qrcode.vue'; //引用Qrcode组件
export default {
components: {
Qrcode //注册Qrcode组件
},
data() {
return {
dimensional:false,
codeUrl: "", // 二维码地址
user_id: ""
};
},
methods: {
// 生成二维码
generateQRCode(){
this.dimensional = true
this.codeUrl = "https://www.baidu.com?user_id=" + this.user_id
},
}
};
</script>
总结
在这个例子中,我们在Qrcode组件中传递了一个value prop,它是一个字符串,表示要生成二维码的内容。您还可以传递其他选项,如width、height、colorDark和colorLight。