vue使用qrcode实现生成二维码和刷新二维码
安装qrcode
首先,确保你的Vue项目已经安装了qrcode.js。你可以使用npm或者yarn来安装:
npm install qrcode
yarn add qrcode
导入qrcode.js
在你的Vue组件中,导入qrcode.js
import QRCode from 'qrcode';
完整代码
话不多说,直接上代码
<template>
<div>
<img :src="qrCodeData" alt="QR Code" style="width:400px" />
<button @click="refreshQRCode">Refresh QR Code</button>
</div>
</template>
<script>
import QRCode from "qrcode";
export default {
data() {
return {
qrCodeData: "",
foregroundColor: "#ff0000", // 前景色,默认为黑色
backgroundColor: "#1714da", // 背景色,默认为白色
};
},
mounted() {
// 初始化生成二维码
const initialText = "https://www.csdn.net/"; // 初始文本
this.generateQRCode(initialText);
},
methods: {
generateQRCode(text) {
const options = {
color: {
dark: this.foregroundColor, // 设置前景色
light: this.backgroundColor, // 设置背景色
},
};
QRCode.toDataURL(text, options)
.then((url) => {
this.qrCodeData = url;
})
.catch((err) => {
console.error(err);
});
},
refreshQRCode() {
const newText = "Your New Text"; // 替换成你想要刷新的新文本
this.generateQRCode(newText);
},
},
};
</script>
<style scoped>
/* 在这里添加你想要的样式 */
</style>