介绍
将一段文字或链接编码成图形,以便光学扫描仪或手机摄像头快速读取。
代码演示
基础使用
设置 text 属性即可渲染一个二维码图片。其内部通过 canvas 来绘制二维码,但最终的呈现是以图片的形式,因此可以覆盖任何东西在二维码上面。
vue
<template>
<s-qrcode text="https://sard.wzt.zone/mobile/" />
</template>呈现的大小
使用 size 属性设置二维码呈现的大小,可以设置为任意尺寸单位。
vue
<template>
<s-qrcode text="https://sard.wzt.zone/mobile/" size="200px" />
</template>自定义颜色
通过设置 color 自定义二维码暗模块颜色, 通过设置 bg-color 自定义二维码亮模块颜色,即背景颜色。
vue
<template>
<div>
<s-qrcode text="https://sard.wzt.zone/mobile/" color="#fd7e14" />
<s-qrcode
style="margin-inline-start: 10px"
text="https://sard.wzt.zone/mobile/"
bg-color="#91ffde"
/>
</div>
</template>添加图标
使用 icon 属性, 可以将一张图片渲染到画布中间,与二维码合并为同一张图片。
vue
<template>
<s-qrcode text="https://sard.wzt.zone/mobile/" :icon="logo" />
</template>
<script setup lang="ts">
import logo from '@/assets/logo.png'
</script>vue
<template>
<s-qrcode text="https://sard.wzt.zone/mobile/" :icon="logo" />
</template>
<script setup lang="js">
import logo from '@/assets/logo.png'
</script>安静区域模块数
可以简单把设置 quiet-zone-modules 当成设置二维码内边距。
vue
<template>
<s-qrcode text="https://sard.wzt.zone/mobile/" :quiet-zone-modules="4" />
</template>错误纠错级别
错误纠错级别越高,二维码抗磨损、抗脏能力越强,同时二维码就越大,可容纳的字符容量越小。
ecl 属性用于设置错误纠错级别。
vue
<template>
<s-segmented v-model="ecl" :options="eclOptions" class="mb-20" />
<s-qrcode text="https://sard.wzt.zone/mobile/" :ecl="ecl" />
</template>
<script setup lang="ts">
import { type QrcodeECL } from 'sard'
import { ref } from 'vue'
const eclOptions: QrcodeECL[] = ['L', 'M', 'Q', 'H']
const ecl = ref<QrcodeECL>('M')
</script>vue
<template>
<s-segmented v-model="ecl" :options="eclOptions" class="mb-20" />
<s-qrcode text="https://sard.wzt.zone/mobile/" :ecl="ecl" />
</template>
<script setup lang="js">
import 'sard'
import { ref } from 'vue'
const eclOptions = ['L', 'M', 'Q', 'H']
const ecl = ref('M')
</script>下面是不同纠错级别的纠错能力表。
| 错误纠错级别 | 错误纠错能力 |
|---|---|
| L | 恢复 7%的数据 |
| M | 恢复 15%的数据 |
| Q | 恢复 25%的数据 |
| H | 恢复 30%的数据 |
API
QrcodeProps
| 属性 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| text | 要编码的字符串数据 | string | - |
| ecl | 错误纠错级别 | 'L' | 'M' | 'Q' | 'H' | 'M' |
| size | 二维码呈现的大小 | string | 160px |
| color | 二维码颜色 | string | #000 |
| bg-color | 二维码背景颜色 | string | #fff |
| quiet-zone-modules | 安静区域模块数 | number | 2 |
| icon | 二维码中图片的地址 | string | - |