QrCode
Generate QR codes from text for sign-in, link sharing, or app downloads. UTF-8 encoding supports Chinese and emoji. The smallest suitable version (1–40) is selected automatically. Add a central icon, render with canvas or SVG, and export PNG or SVG downloads.
The component includes its own ISO/IEC 18004 encoder without a third-party encoding dependency.
Import
import { HuiQrCode } from '@nscode/handy-ui'
import type { QrCodeExpose } from '@nscode/handy-ui'
Basic usage
value contains the text to encode. Defaults are a 100px code, 12px of white padding, and an outer border.
<template>
<HuiQrCode value="https://example.com" />
</template>
The content can be arbitrary text, including Chinese:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiQrCode } from '@nscode/handy-ui'
const text = ref('你好,HandyUI 二维码')
</script>
<template>
<div style="margin-bottom: 12px">
<HuiQrCode :value="text" />
</div>
<HuiInput v-model="text" />
</template>
Animated patterns
Set effect="morph" to generate a colored pixel pattern from the content. Click to rotate and gather it into a real colored QR code; click again to reverse the transition. shape supports trees, hearts, and flowers. The default random chooses deterministically from the content, so rerenders do not change the pattern or colors. Both canvas and SVG are supported.
Animated patterns require the optional three dependency:
pnpm add three
After installation, enable animated patterns in your application entry:
import { enableQrCodeMorph } from '@nscode/handy-ui/qr-code-morph'
enableQrCodeMorph()
A normal QR code is shown when the feature is not enabled, loading fails, or WebGL is unavailable. In development, each missing-enable or loading-failure reason is warned once. The regular QR-code entry does not reference this optional dependency.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiQrCode, HuiSpace } from '@nscode/handy-ui'
const canvasView = ref('shape')
const svgView = ref('shape')
</script>
<template>
<HuiSpace wrap size="large" align="start">
<HuiSpace direction="vertical" align="center">
<HuiQrCode
value="https://example.com"
effect="morph"
shape="tree"
:size="240"
@view-change="canvasView = $event"
/>
<span>Tree / canvas / {{ canvasView === 'shape' ? 'Pattern' : 'QR code' }}</span>
</HuiSpace>
<HuiSpace direction="vertical" align="center">
<HuiQrCode
value="https://example.com"
type="svg"
effect="morph"
shape="heart"
:size="240"
@view-change="svgView = $event"
/>
<span>Heart / svg / {{ svgView === 'shape' ? 'Pattern' : 'QR code' }}</span>
</HuiSpace>
</HuiSpace>
</template>
- The default
effect="none"displays an ordinary QR code. Morph patterns are generated without image URLs. In morph mode, a content-derived palette replacescolor, keeping QR modules dark.background-colorstill sets the background. animation-durationdefaults to 500ms; 0 switches immediately. Reduced-motion preferences also disable the transition. Clicking again during animation smoothly reverses it.view-changefires when a transition completes, with'shape'or'qrcode'; it does not fire on initial rendering. Changes to content, shape, background, or duration restore the pattern view.- Loading, expiry, or excessive content takes precedence and prevents toggling. Missing WebGL or rendering failures fall back to a scannable QR code.
- Focus the toggle area with Tab and use Enter/Space to switch views.
toDataURL()andtoSvgString()always export the colored QR code, including icons, without changing the display size. A size of at least 200px is recommended for morph patterns.
Compare every shape below. Edit the content to see another stable palette:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiQrCode, HuiSpace } from '@nscode/handy-ui'
const value = ref('https://example.com')
const shapes = ['tree', 'heart', 'flower', 'random'] as const
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput v-model="value" aria-label="QR content" />
<HuiSpace wrap size="large">
<HuiSpace v-for="shape in shapes" :key="shape" direction="vertical" align="center">
<HuiQrCode :value="value" effect="morph" :shape="shape" :size="200" />
<span>{{ shape }}</span>
</HuiSpace>
</HuiSpace>
</HuiSpace>
</template>
<script setup lang="ts">
import { HuiQrCode, HuiSpace } from '@nscode/handy-ui'
</script>
<template>
<HuiSpace wrap align="start" size="large">
<HuiSpace direction="vertical" align="center">
<HuiQrCode value="快速旋转" effect="morph" :animation-duration="250" :size="200" />
<span>250ms</span>
</HuiSpace>
<HuiSpace direction="vertical" align="center">
<HuiQrCode value="立即切换" effect="morph" :animation-duration="0" :size="200" />
<span>0ms</span>
</HuiSpace>
</HuiSpace>
</template>
Adding an icon
icon-src supplies the central icon URL. The icon covers QR modules, so an icon automatically selects the highest error correction level H when error-correction-level is omitted, allowing recovery from approximately 30% damaged codewords. An explicit level takes precedence.
icon-size sets the side length (40px by default). icon-background-color sets its background (white), and icon-border-radius sets the background/image corner radius (4px). The image preserves its ratio, is centered in the icon box, and is clipped to the rounded corners.
<template>
<HuiSpace wrap>
<HuiQrCode value="https://example.com" icon-src="/logo.png" />
<HuiQrCode
value="https://example.com"
icon-src="/logo.png"
:size="160"
:icon-size="48"
icon-background-color="#f0f5ff"
:icon-border-radius="12"
/>
</HuiSpace>
</template>
Keep icons small: a side length no more than 40% of size is recommended (the default is 40 for a size of 100). Larger icons may prevent scanning.
Size and padding
sizeis the code's side length in pixels, excluding padding, and defaults to 100. Total component width issize + padding × 2, plus the two 1px outer borders.paddingis the quiet zone filled withbackground-color, defaulting to 12px. Numbers are pixels; CSS strings such as'1em'are accepted. Scanners use the quiet zone to locate the code, so avoid zero padding on dark or patterned backgrounds.borderedcontrols the outer border and defaults to true.
<template>
<HuiSpace wrap align="end">
<HuiQrCode value="size 160" :size="160" />
<HuiQrCode value="padding 24" :padding="24" />
<HuiQrCode value="无外框" :bordered="false" />
</HuiSpace>
</template>
The first row compares size values; the second compares padding as zero, a number, and a CSS string:
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap align="end">
<HuiQrCode value="https://example.com" :size="60" />
<HuiQrCode value="https://example.com" :size="80" />
<HuiQrCode value="https://example.com" />
<HuiQrCode value="https://example.com" :size="140" />
</HuiSpace>
<HuiSpace wrap align="end">
<HuiQrCode value="https://example.com" :padding="0" />
<HuiQrCode value="https://example.com" :padding="6" />
<HuiQrCode value="https://example.com" padding="1em" />
<HuiQrCode value="https://example.com" :padding="32" :bordered="false" />
</HuiSpace>
</HuiSpace>
</template>
size is a pixel length rather than the large/default/small presets of other components, and does not follow HuiConfigProvider's size.
Colors
color sets the module color (default #000), and background-color sets the background (default #FFF).
<template>
<HuiSpace wrap>
<HuiQrCode value="主色码点" color="#1677ff" background-color="#f0f5ff" />
<HuiQrCode value="绿色码点" color="#237804" background-color="#f6ffed" />
<HuiQrCode value="紫色码点" color="#531dab" />
<HuiQrCode value="暖色底" color="#873800" background-color="#fff7e6" />
</HuiSpace>
</template>
These prop defaults are fixed and do not change in dark themes. QR codes need dark modules on a light background; many scanners cannot read inverted codes. Dark themes therefore still display a black-on-white code like a white card. Custom colors should retain strong contrast, with modules much darker than the background. The border, corner radius, and status overlay use theme variables and adapt to the theme.
Error correction
error-correction-level has four levels:
| Level | Recoverable codewords | Description |
|---|---|---|
| L | Approximately 7% | Fewest modules; easiest to scan |
| M | Approximately 15% | Default without an icon |
| Q | Approximately 25% | |
| H | Approximately 30% | Default with an icon |
Higher levels tolerate more occlusion and damage but require more modules for the same content. These codes encode identical content at L, M, Q, and H respectively:
<template>
<HuiSpace wrap size="large">
<HuiSpace direction="vertical" align="center">
<HuiQrCode value="https://example.com/docs/qrcode" error-correction-level="L" />
<span class="caption">L</span>
</HuiSpace>
<HuiSpace direction="vertical" align="center">
<HuiQrCode value="https://example.com/docs/qrcode" error-correction-level="M" />
<span class="caption">M (default)</span>
</HuiSpace>
<HuiSpace direction="vertical" align="center">
<HuiQrCode value="https://example.com/docs/qrcode" error-correction-level="Q" />
<span class="caption">Q</span>
</HuiSpace>
<HuiSpace direction="vertical" align="center">
<HuiQrCode value="https://example.com/docs/qrcode" error-correction-level="H" />
<span class="caption">H</span>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.caption {
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Rendering
type defaults to canvas, scaling the canvas by devicePixelRatio for sharp high-density rendering. Browser zoom or moving between screens redraws at the new ratio. type="svg" renders an <svg> with all modules in one path, preserving sharpness for scaling/printing and allowing CSS selection. Both types support icons.
<template>
<HuiSpace wrap>
<HuiQrCode value="canvas 渲染" />
<HuiQrCode value="svg 渲染" type="svg" />
<HuiQrCode value="canvas 带图标" icon-src="/logo.png" />
<HuiQrCode value="svg 带图标" type="svg" icon-src="/logo.png" />
</HuiSpace>
</template>
Downloading QR codes
Call toDataURL through a ref and use an <a download> to save the result. Both rendering types export PNG, JPEG, WebP, and SVG. Exports include padding and icons, but exclude the outer border and status overlay.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiQrCode, HuiSpace } from '@nscode/handy-ui'
import type { QrCodeExpose } from '@nscode/handy-ui'
const qrRef = ref<QrCodeExpose | null>(null)
const download = async (type: 'image/png' | 'image/svg+xml') => {
const url = await qrRef.value?.toDataURL(type, { scale: 4 })
if (!url) return
const a = document.createElement('a')
a.href = url
a.download = type === 'image/png' ? 'qrcode.png' : 'qrcode.svg'
a.click()
}
</script>
<template>
<HuiSpace wrap>
<HuiQrCode ref="qrRef" value="https://example.com" icon-src="/logo.png" />
<HuiButton type="primary" icon="download" @click="download('image/png')"
>Download PNG</HuiButton
>
<HuiButton icon="download" @click="download('image/svg+xml')">Download SVG</HuiButton>
</HuiSpace>
</template>
- PNG, JPEG, and WebP side length is
(size + padding × 2) × scale.scaledefaults to 2 and can be increased for printing. - Export waits for icons to load. For a cross-origin icon, set
icon-cross-origin="anonymous"and configure its server to returnAccess-Control-Allow-Origin. Otherwise the canvas is tainted: PNG export rejects with a console warning. - SVG export is not restricted by canvas cross-origin rules, but its icon references the original URL rather than embedding it. Use
toSvgString()for SVG source, such as for inline display or sending to a server.
JPEG and WebP accept quality from 0 to 1. This example displays the exported image and size; toSvgString() returns SVG source text:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiQrCode, HuiSpace } from '@nscode/handy-ui'
import type { QrCodeExpose, QrCodeExportType } from '@nscode/handy-ui'
const qrRef = ref<QrCodeExpose | null>(null)
const preview = ref('')
const info = ref('')
const exportImage = async (type: QrCodeExportType) => {
const url = await qrRef.value?.toDataURL(type, { scale: 2, quality: 0.8 })
if (!url) return
preview.value = url
info.value = `${type}, data URL: ${url.length} characters`
}
const exportSvgString = () => {
const svg = qrRef.value?.toSvgString() ?? ''
preview.value = ''
info.value = `toSvgString() returned ${svg.length} characters, starting with ${svg.slice(0, 40)}…`
}
</script>
<template>
<HuiSpace wrap align="start">
<HuiQrCode ref="qrRef" value="https://example.com" color="#1677ff" />
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<HuiButton size="small" @click="exportImage('image/png')">PNG</HuiButton>
<HuiButton size="small" @click="exportImage('image/jpeg')">JPEG</HuiButton>
<HuiButton size="small" @click="exportImage('image/webp')">WebP</HuiButton>
<HuiButton size="small" @click="exportImage('image/svg+xml')">SVG</HuiButton>
<HuiButton size="small" @click="exportSvgString">toSvgString</HuiButton>
</HuiSpace>
<span>{{ info || 'Use the buttons above to export' }}</span>
<img v-if="preview" :src="preview" alt="Exported QR code" style="width: 124px" />
</HuiSpace>
</HuiSpace>
</template>
Status
status accepts active (default), loading, and expired:
loading: a translucent overlay withHuiSpin; the root hasaria-busy="true".expired: localized expiry text and a refresh button. The button emitsrefresh; fetch new content in its handler. Override text withexpired-textandrefresh-text.
<template>
<HuiSpace wrap size="large">
<HuiSpace direction="vertical" align="center">
<HuiQrCode value="https://example.com" />
<span class="caption">active</span>
</HuiSpace>
<HuiSpace direction="vertical" align="center">
<HuiQrCode value="https://example.com" status="loading" />
<span class="caption">loading</span>
</HuiSpace>
<HuiSpace direction="vertical" align="center">
<HuiQrCode value="https://example.com" status="expired" />
<span class="caption">expired</span>
</HuiSpace>
<HuiSpace direction="vertical" align="center">
<HuiQrCode
value="https://example.com"
status="expired"
expired-text="Sign-in code expired"
refresh-text="Get a new code"
/>
<span class="caption">Custom status text</span>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.caption {
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Click Refresh to enter loading, then receive new content after one second:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiQrCode } from '@nscode/handy-ui'
import type { QrCodeStatus } from '@nscode/handy-ui'
const value = ref('https://example.com/login?t=1')
const status = ref<QrCodeStatus>('expired')
const refresh = async () => {
status.value = 'loading'
value.value = await fetchLoginUrl()
status.value = 'active'
}
// Replace with your API
const fetchLoginUrl = () =>
new Promise<string>((resolve) =>
setTimeout(() => resolve(`https://example.com/login?t=${Date.now()}`), 1000)
)
</script>
<template>
<HuiQrCode :value="value" :status="status" @refresh="refresh" />
</template>
Replace the entire overlay with the status slot. It receives status and a refresh callback that emits the refresh event:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiQrCode } from '@nscode/handy-ui'
import type { QrCodeStatus } from '@nscode/handy-ui'
const value = ref('https://example.com/login?t=1')
const status = ref<QrCodeStatus>('expired')
const refresh = async () => {
status.value = 'loading'
value.value = await fetchLoginUrl()
status.value = 'active'
}
// Replace with your API
const fetchLoginUrl = () =>
new Promise<string>((resolve) =>
setTimeout(() => resolve(`https://example.com/login?t=${Date.now()}`), 1000)
)
</script>
<template>
<HuiQrCode :value="value" :status="status" @refresh="refresh">
<template #status="{ status, refresh }">
<span v-if="status === 'loading'">Generating…</span>
<a v-else href="javascript:;" @click="refresh">Expired; click to refresh</a>
</template>
</HuiQrCode>
</template>
Content limits
Version 40 capacity is 2953 bytes at L, 2331 at M, 1663 at Q, and 1273 at H. A Chinese character typically uses 3 UTF-8 bytes, so H holds approximately 424 such characters. Excessive content displays a localized message in place without throwing, configurable with overflow-text, and produces an [HandyUI] QrCode generation warning.
For excessive content, lower the correction level or encode a short link instead. Longer content produces denser patterns that are harder to scan; keeping content within a few hundred bytes is generally recommended.
Use the button to switch to 3000 characters, exceeding level M capacity:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiQrCode, HuiSpace } from '@nscode/handy-ui'
const short = 'https://example.com'
const value = ref(short)
const toggle = () => {
value.value = value.value === short ? 'a'.repeat(3000) : short
}
</script>
<template>
<HuiSpace wrap align="center">
<HuiQrCode :value="value" overflow-text="Content is too long" />
<HuiButton @click="toggle">{{
value === short ? 'Use 3000 characters' : 'Use the short link'
}}</HuiButton>
</HuiSpace>
</template>
Accessibility
- The QR code (
<canvas>or<svg>) hasrole="img"and a localizedaria-labelcontaining its value, or a generic QR-code label when empty. - Set
altoraria-labelto a meaningful description such as Scan to sign in.aria-labeltakes precedence. This avoids reading long encoded URLs aloud. - The expired refresh control is a native
<button>, focusable with Tab and activated by Enter/Space. Loading feedback hasrole="status".
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| value | string | '' | QR content encoded as UTF-8 |
| size | number | 100 | Code side length (px), excluding padding; invalid nonpositive values warn and use 100 |
| padding | number | string | 12 | Quiet-zone padding, using numbers as pixels and filled with background-color |
| color | string | '#000' | Module color; does not adapt to dark themes |
| background-color | string | '#FFF' | Background including padding; does not adapt to dark themes |
| effect | 'none' | 'morph' | 'none' | Ordinary QR display or animated morph effect |
| shape | 'tree' | 'heart' | 'flower' | 'random' | 'random' | Pattern type, only in morph mode; random is chosen deterministically from content |
| animation-duration | number | 500 | Transition duration in milliseconds; 0 switches immediately |
| icon-src | string | - | Central icon URL |
| icon-size | number | 40 | Icon side length (px), clamped to size |
| icon-background-color | string | '#FFF' | Icon background color |
| icon-border-radius | number | 4 | Icon background/image radius (px), capped at half the icon side length |
| icon-cross-origin | '' | 'anonymous' | 'use-credentials' | - | Same as <img crossorigin>; use 'anonymous' to export PNG with a cross-origin icon |
| error-correction-level | 'L' | 'M' | 'Q' | 'H' | 'M' ('H' with icon-src) | Explicit correction level takes precedence; invalid values warn and fall back |
| type | 'canvas' | 'svg' | 'canvas' | Rendering type |
| bordered | boolean | true | Whether to display the outer border |
| status | 'active' | 'loading' | 'expired' | 'active' | QR state |
| expired-text | string | Locale-dependent | Expiry message |
| refresh-text | string | Locale-dependent | Expired-state refresh button text |
| overflow-text | string | Locale-dependent | Message when content exceeds QR capacity |
| alt | string | - | Alternative text used as the QR code's aria-label |
| aria-label | string | - | Accessible label, taking precedence over alt; defaults to a localized label with the encoded value |
Events
| Event | Parameters | Description |
|---|---|---|
| refresh | () | Emitted when the refresh button is clicked in expired state |
| view-change | (view: QrCodeView) | Emitted after a view transition completes, not on initial rendering |
Slots
| Slot | Scope | Description |
|---|---|---|
| status | { status: 'loading' | 'expired', refresh: () => void } | Overlay content when status is not active; defaults to loading feedback or expiry text with refresh |
Methods
Call through the HuiQrCode ref.
| Method | Parameters | Description | | ----------- | ---------------------------------------------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | toDataURL | (type?: QrCodeExportType, options?: QrCodeExportOptions) | Promise<string> | Export a data URL (PNG by default), including padding/icons and waiting for icon loading. Rejects for excessive content or tainted canvas, warning for the latter | | toSvgString | - | string | Export SVG source including background, padding, and icons; returns an empty string for excessive content |
Types
import type {
QrCodeProps,
QrCodeEmits,
QrCodeExpose,
QrCodeErrorCorrectionLevel,
QrCodeType,
QrCodeStatus,
QrCodeEffect,
QrCodeShape,
QrCodeView,
QrCodeExportType,
QrCodeExportOptions,
QrCodeIconCrossOrigin
} from '@nscode/handy-ui'
type QrCodeErrorCorrectionLevel = 'L' | 'M' | 'Q' | 'H'
type QrCodeType = 'canvas' | 'svg'
type QrCodeStatus = 'active' | 'loading' | 'expired'
type QrCodeEffect = 'none' | 'morph'
type QrCodeShape = 'tree' | 'heart' | 'flower' | 'random'
type QrCodeView = 'shape' | 'qrcode'
type QrCodeExportType = 'image/png' | 'image/jpeg' | 'image/webp' | 'image/svg+xml'
type QrCodeIconCrossOrigin = '' | 'anonymous' | 'use-credentials'
interface QrCodeExportOptions {
/** Export scale, default 2; only applies to PNG, JPEG, and WebP */
scale?: number
/** JPEG/WebP quality from 0 to 1 */
quality?: number
}
interface QrCodeExpose {
toDataURL: (type?: QrCodeExportType, options?: QrCodeExportOptions) => Promise<string>
toSvgString: () => string
}