vue3-next-qrcode:一个功能强大的 Vue 3 二维码组件库
前言
在现代 Web 应用开发中,二维码已经成为不可或缺的功能之一。无论是分享链接、支付场景还是身份验证,二维码都扮演着重要角色。今天给大家介绍一个功能强大的 Vue 3 二维码组件库 ------ vue3-next-qrcode,它不仅支持基础的二维码生成,还提供了 LOGO、GIF 背景、SSR 等高级特性。
项目亮点
🎯 核心特性
- 🏄🏼♂️ 基于 Vue 3 Composition API:完全拥抱 Vue 3 生态,易于使用和集成
- 🎯 TypeScript 支持:使用 TypeScript 构建,提供完整的类型定义
- 🚀 SSR 支持:完美支持 Nuxt 3 和 Nuxt 2 服务端渲染
- 🎨 Composable API :提供
useQRCodeHook,灵活生成二维码 - ♿ 无障碍支持:内置 ARIA 标签和键盘导航
- 🎭 GIF 背景:支持动态 GIF 背景,并自动缓存优化性能
- 📦 Tree-shaking:优化打包体积,按需加载
- 🔄 自动刷新:文本变化时自动重新生成二维码
- 💾 内置下载:一键下载生成的二维码
快速开始
安装
bash
# npm
npm install vue3-next-qrcode
# yarn
yarn add vue3-next-qrcode
# pnpm
pnpm add vue3-next-qrcode
基础用法
vue
<script setup lang="ts">
import { Vue3NextQrcode } from 'vue3-next-qrcode'
import 'vue3-next-qrcode/es/style.css'
</script>
<template>
<Vue3NextQrcode text="https://github.com/XiaoDaiGua-Ray/vue3-next-qrcode" />
</template>
就这么简单!一个基础的二维码就生成了。
进阶功能
1. 自定义样式
vue
<template>
<Vue3NextQrcode
text="你好世界"
:size="300"
:margin="20"
colorDark="#000000"
colorLight="#ffffff"
:correctLevel="3"
/>
</template>
2. 添加 Logo
vue
<template>
<Vue3NextQrcode
text="https://example.com"
logoImage="https://example.com/logo.png"
:logoScale="0.3"
:logoMargin="10"
:logoCornerRadius="8"
/>
</template>
3. 使用 GIF 背景(亮点功能!)
这是一个非常酷的功能,可以让你的二维码动起来:
vue
<template>
<Vue3NextQrcode
text="动态二维码"
:gifBackgroundURL="gifUrl"
:dotScale="0.5"
colorDark="#64d9d6"
/>
</template>
<script setup>
const gifUrl = 'https://example.com/background.gif'
</script>
4. 状态管理
支持加载中、错误等状态,提供更好的用户体验:
vue
<template>
<div>
<!-- 加载状态 -->
<Vue3NextQrcode text="加载中..." status="loading" />
<!-- 错误状态 -->
<Vue3NextQrcode
text="错误"
status="error"
errorDescription="二维码已过期"
errorActionDescription="重新加载"
:onReload="handleReload"
/>
<!-- 自定义加载插槽 -->
<Vue3NextQrcode text="自定义加载" status="loading">
<template #loading>
<div class="custom-spinner">加载中...</div>
</template>
</Vue3NextQrcode>
</div>
</template>
5. 下载二维码
vue
<template>
<div>
<Vue3NextQrcode ref="qrcodeRef" text="下载我!" />
<button @click="handleDownload">下载二维码</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const qrcodeRef = ref()
const handleDownload = async () => {
try {
await qrcodeRef.value?.downloadQRCode('my-qrcode.png')
console.log('下载成功!')
} catch (error) {
console.error('下载失败:', error)
}
}
</script>
🎨 Composable API(v4.0.0 新特性)
v4.0.0 版本引入了 useQRCode Composable,提供了更灵活的编程式二维码生成方式:
vue
<script setup lang="ts">
import { ref } from 'vue'
import { useQRCode } from 'vue3-next-qrcode'
const { qrcodeURL, isLoading, error, generate, clear } = useQRCode()
const text = ref('你好世界')
const handleGenerate = async () => {
await generate({
text: text.value,
size: 300,
margin: 20,
colorDark: '#000000',
colorLight: '#ffffff',
})
}
</script>
<template>
<div>
<input v-model="text" placeholder="输入文本" />
<button @click="handleGenerate" :disabled="isLoading">
{{ isLoading ? '生成中...' : '生成' }}
</button>
<button @click="clear">清除</button>
<div v-if="error" class="error">{{ error.message }}</div>
<img v-if="qrcodeURL" :src="qrcodeURL" alt="二维码" />
</div>
</template>
这种方式特别适合需要动态控制二维码生成时机的场景。
🌐 SSR 支持(Nuxt)
对于使用 Nuxt 的开发者,vue3-next-qrcode 提供了完善的 SSR 支持方案。
方法 1:使用 ClientOnly(推荐)
vue
<template>
<ClientOnly>
<QRCodeClient text="你好 Nuxt 3" />
<template #fallback>
<div>加载二维码中...</div>
</template>
</ClientOnly>
</template>
<script setup>
import { QRCodeClient } from 'vue3-next-qrcode'
import 'vue3-next-qrcode/es/style.css'
</script>
方法 2:动态导入
vue
<template>
<LazyQRCode v-if="mounted" text="你好 Nuxt" />
</template>
<script setup>
import { ref, onMounted } from 'vue'
const LazyQRCode = defineAsyncComponent(() =>
import('vue3-next-qrcode').then((m) => m.Vue3NextQrcode),
)
const mounted = ref(false)
onMounted(() => {
mounted.value = true
})
</script>
Nuxt 配置
typescript
// nuxt.config.ts
export default defineNuxtConfig({
build: {
transpile: ['vue3-next-qrcode'],
},
vite: {
optimizeDeps: {
include: ['vue3-next-qrcode'],
},
},
})
🎨 CSS 变量自定义样式
支持通过 CSS 变量进行深度样式定制:
vue
<template>
<Vue3NextQrcode
text="样式化二维码"
:defineProvider="{
'--r-qrcode-primary-color': '#1677ff',
'--r-qrcode-primary-color-2': '#69b1ff',
'--r-qrcode-spin-size': '4px',
}"
/>
</template>
可用的 CSS 变量包括:
--r-qrcode-width:二维码宽度--r-qrcode-height:二维码高度--r-qrcode-border-radius:边框圆角--r-qrcode-mask-color:遮罩层颜色--r-qrcode-primary-color:主题色--r-qrcode-primary-color-2:次要主题色--r-qrcode-spin-size:加载动画大小
v4.0.0 重大更新
最新的 v4.0.0 版本带来了许多重要改进:
破坏性变更
- CSS 类名前缀从
ray-qrcode统一改为r-qrcode img_tag属性改为data-component
新增特性
- useQRCode Composable:提供更灵活的二维码生成能力
- QRCodeClient 组件:专为 Nuxt SSR 环境优化
- GIF 背景缓存机制:避免重复加载相同的 GIF,提升性能
- 完整的 ARIA 无障碍支持:包括 role、aria-label、键盘导航
- 优化的 TypeScript 类型定义:提供更好的类型推导
性能优化
- 使用 Composition API 重构组件内部实现
- 使用
shallowRef优化大对象性能 - 优化 watcher 管理,避免内存泄漏
- 使用
fetchAPI 替代XMLHttpRequest,更好地支持 SSR - 添加防止并发渲染的锁机制,提升稳定性
开发体验
- 添加 ESLint 和 Prettier 配置
- 添加 GitHub Actions CI 工作流
- 优化
package.json的exports字段 - 添加
sideEffects配置,优化 tree-shaking
实际应用场景
1. 动态链接分享
vue
<script setup>
import { ref, computed } from 'vue'
const baseUrl = 'https://example.com/share'
const userId = ref('12345')
const shareUrl = computed(() => `${baseUrl}?user=${userId.value}`)
</script>
<template>
<Vue3NextQrcode :text="shareUrl" :watchText="true" :size="200" />
</template>
2. 支付二维码
vue
<script setup>
const paymentInfo = ref({
amount: 100,
orderId: 'ORDER123',
})
const paymentUrl = computed(
() =>
`payment://pay?amount=${paymentInfo.value.amount}&order=${paymentInfo.value.orderId}`,
)
const handlePaymentSuccess = (dataURL) => {
console.log('支付二维码生成成功')
// 可以将 dataURL 发送到后端保存
}
</script>
<template>
<Vue3NextQrcode
:text="paymentUrl"
:size="300"
logoImage="/logo.png"
:logoScale="0.2"
:onSuccess="handlePaymentSuccess"
/>
</template>
3. 带状态的二维码
vue
<script setup>
import { ref, onMounted } from 'vue'
const qrStatus = ref('loading')
const qrText = ref('')
onMounted(async () => {
try {
// 模拟从后端获取二维码内容
const response = await fetch('/api/qrcode')
const data = await response.json()
qrText.value = data.url
qrStatus.value = undefined
} catch (error) {
qrStatus.value = 'error'
}
})
const handleReload = async () => {
qrStatus.value = 'loading'
// 重新加载逻辑
}
</script>
<template>
<Vue3NextQrcode
:text="qrText"
:status="qrStatus"
errorDescription="二维码加载失败"
:onReload="handleReload"
/>
</template>
性能优化建议
-
使用 watchText 控制更新 :如果二维码内容不需要实时更新,可以设置
:watchText="false"来避免不必要的重新渲染 -
GIF 背景缓存:v4.0.0 已经内置了 GIF 缓存机制,相同的 GIF URL 只会加载一次
-
按需加载:在 Nuxt 或大型应用中,使用动态导入来减少初始加载体积
-
合理设置尺寸:根据实际需求设置合适的二维码尺寸,避免生成过大的图片
总结
vue3-next-qrcode 是一个功能完善、性能优秀的 Vue 3 二维码组件库。无论是简单的二维码生成,还是复杂的业务场景(如带 Logo、GIF 背景、状态管理等),它都能轻松应对。
特别是 v4.0.0 版本带来的 Composable API 和 SSR 优化,让它在现代 Vue 3 应用中更加得心应手。如果你正在寻找一个强大的 Vue 3 二维码解决方案,不妨试试 vue3-next-qrcode!
相关链接
- GitHub:github.com/XiaoDaiGua-...
- NPM:www.npmjs.com/package/vue...
- 在线示例:查看项目 README 中的示例图片
如果这篇文章对你有帮助,欢迎点赞收藏!如果在使用过程中遇到问题,也欢迎在 GitHub 提 Issue 或 PR。