vue实现生成二维码
生成二维码的方法
在Vue中生成二维码可以通过第三方库实现,以下是两种常用方式:
使用qrcode库
安装依赖:
npm install qrcode
组件实现:
<template>
<div>
<canvas ref="qrcodeCanvas"></canvas>
</div>
</template>
<script>
import QRCode from 'qrcode'
export default {
props: {
text: {
type: String,
required: true
}
},
mounted() {
QRCode.toCanvas(this.$refs.qrcodeCanvas, this.text, {
width: 200,
margin: 1
}, (error) => {
if (error) console.error(error)
})
}
}
</script>
使用vue-qrcode组件
安装依赖:
npm install @chenfengyuan/vue-qrcode
组件使用:
<template>
<div>
<vue-qrcode :value="qrText" :options="{ width: 200 }"></vue-qrcode>
</div>
</template>
<script>
import VueQrcode from '@chenfengyuan/vue-qrcode'
export default {
components: { VueQrcode },
data() {
return {
qrText: 'https://example.com'
}
}
}
</script>
自定义二维码样式
可以通过修改配置选项来自定义二维码外观:
QRCode.toCanvas(this.$refs.qrcodeCanvas, this.text, {
width: 200,
color: {
dark: '#000000', // 二维码颜色
light: '#ffffff' // 背景色
},
margin: 2
})
生成二维码图片
如果需要生成图片文件而非canvas:

QRCode.toDataURL(this.text, {
width: 200
}, (err, url) => {
if (err) throw err
this.qrImageUrl = url
})
注意事项
- 二维码内容长度会影响生成复杂度,过长的文本可能无法正确识别
- 移动端使用时需考虑不同设备的DPI差异
- 生成后可通过canvas或img标签直接显示在页面上






