Skip to content

useBase64

类别
导出大小
794 B
最近修改
2 days ago

响应式 Base64 转换。支持纯文本、缓冲区、文件、画布、对象、映射、集合和图片。

🌐 Reactive base64 transforming. Supports plain text, buffer, files, canvas, objects, maps, sets and images.

示例

Text Input
Base64
Buffer Input
new ArrayBuffer(1024)
Base64
File Input
Base64
Image Input
Base64

用法

🌐 Usage

ts
import { 
useBase64
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
text
=
shallowRef
('')
const {
base64
,
promise
,
execute
} =
useBase64
(
text
)

支持的输入类型

🌐 Supported Input Types

  • string - 纯文本
  • Blob - 文件或二进制大对象数据
  • ArrayBuffer - 二进制数据
  • HTMLCanvasElement - 画布元素
  • HTMLImageElement - 图片元素
  • Object / Array / Map / Set - 序列化为 JSON

返回值

🌐 Return Values

属性描述
base64生成的 base64 字符串
promise当前转换的 Promise
execute手动触发转换

数据 URL 格式

🌐 Data URL Format

默认情况下,输出是数据 URL 格式(例如,data:text/plain;base64,...)。设置 dataUrl: false 可获取原始 base64。

🌐 By default, the output is in Data URL format (e.g., data:text/plain;base64,...). Set dataUrl: false to get raw base64.

ts
const { 
base64
} = useBase64(text, {
dataUrl
: false })
// Returns raw base64 without the data URL prefix

画布和图片选项

🌐 Canvas and Image Options

在转换画布或图片元素时,你可以指定 MIME 类型和质量。

🌐 When transforming canvas or image elements, you can specify the MIME type and quality.

ts
const 
canvas
=
document
.
querySelector
('canvas')
const {
base64
} = useBase64(
canvas
, {
type
: 'image/jpeg', // MIME type
quality
: 0.8, // Image quality (0-1, for jpeg/webp)
})

自定义序列化器

🌐 Custom Serializer

对于对象、数组、映射和集合,你可以提供自定义序列化器。否则,数据将使用 JSON.stringify 进行序列化(映射会被转换为对象,集合会被转换为数组)。

🌐 For objects, arrays, maps and sets, you can provide a custom serializer. Otherwise, the data will be serialized using JSON.stringify (maps are converted to objects, sets to arrays).

ts
const 
data
=
shallowRef
({
foo
: 'bar' })
const {
base64
} = useBase64(
data
, {
serializer
:
v
=>
JSON
.
stringify
(
v
, null, 2),
})