安装依赖
npm install qrcode
在Vue中使用
< template> < div class = "qr-code-generator" > < inputv-model= "text" type = "text" placeholder = "请输入要生成二维码的内容" class = "input-box" /> < button @click= "generateQRCode" class = "generate-btn" > 生成二维码< /button> < canvas ref = "qrCanvas" class = "qr-canvas" > < /canvas> < /div>
< /template> < script>
import QRCode from "qrcode" ; export default { name: "QRCodeGenerator" ,data ( ) { return { text: "" , } ; } ,methods: { generateQRCode ( ) { const canvas = this.$refs .qrCanvas; if ( this.text.trim( )) { QRCode.toCanvas( canvas, this.text, { errorCorrectionLevel: "H" } , ( error) = > { if ( error) { console.error( "二维码生成失败" , error) ; } } ) ; } else { alert( "请输入内容" ) ; } } ,} ,//下载图片downloadQRCode ( ) { const canvas = this.$refs .qrCanvas; const url = canvas.toDataURL( ) ; const link = document.createElement( "a" ) ; link.href = url; link.download = "qrcode.png" ; link.click( ) ; } ;
} ;
< /script> < style scoped>
.qr-code-generator { display: flex; flex-direction: column ; align-items: center; padding: 20px;
} .input-box { padding: 10px; width: 300px; margin-bottom: 20px; border: 1px solid border-radius: 5px;
} .generate-btn { padding: 10px 20px; border: none; background-color: color: white; cursor: pointer; border-radius: 5px;
} .qr-canvas { margin-top: 20px;
}
< /style>
拓展
QRCode.toCanvas( canvas, this.text, { width: 300 ,color: { dark: "#000" , // 二维码颜色light: "#fff" , // 背景颜色} ,
} ) ;
支持多种生成方式 通过 v-if 或 v-show 切换不同生成方式,比如直接展示在 标签中:
QRCode.toDataURL( "your text" ) .then(( url) = > { this.imageSrc = url;
} ) ;