vue实现生成二维码
使用qrcode.vue库生成二维码
安装qrcode.vue库:
npm install qrcode.vue --save
在Vue组件中使用:
<template>
<qrcode-vue :value="qrValue" :size="size" level="H" />
</template>
<script>
import QrcodeVue from 'qrcode.vue'
export default {
components: { QrcodeVue },
data() {
return {
qrValue: 'https://example.com',
size: 200
}
}
}
</script>
使用vue-qrcode库生成二维码
安装vue-qrcode库:
npm install @chenfengyuan/vue-qrcode --save
在Vue组件中使用:

<template>
<vue-qrcode :value="qrValue" :options="{ width: 200 }" />
</template>
<script>
import VueQrcode from '@chenfengyuan/vue-qrcode'
export default {
components: { VueQrcode },
data() {
return {
qrValue: 'https://example.com'
}
}
}
</script>
使用原生QRCode.js生成二维码
安装QRCode.js:
npm install qrcode --save
在Vue组件中使用:

<template>
<div ref="qrCode"></div>
</template>
<script>
import QRCode from 'qrcode'
export default {
data() {
return {
qrValue: 'https://example.com'
}
},
mounted() {
QRCode.toCanvas(this.$refs.qrCode, this.qrValue, {
width: 200
}, (error) => {
if (error) console.error(error)
})
}
}
</script>
自定义二维码样式
通过QRCode.js可以自定义二维码样式:
QRCode.toCanvas(this.$refs.qrCode, {
text: this.qrValue,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.H
}, (error) => {
if (error) console.error(error)
})
生成可下载的二维码
生成可下载的二维码图片:
methods: {
downloadQR() {
QRCode.toDataURL(this.qrValue, {
width: 400,
margin: 2
}, (err, url) => {
if (err) return console.error(err)
const link = document.createElement('a')
link.href = url
link.download = 'qrcode.png'
link.click()
})
}
}
响应式二维码尺寸
根据屏幕宽度自动调整二维码大小:
computed: {
qrSize() {
return Math.min(window.innerWidth * 0.8, 400)
}
},
watch: {
qrSize(newSize) {
this.generateQRCode(newSize)
}
}






