在 Vite + Vue + TypeScript 中,你可以使用 btoa
和 atob
函数进行 Base64 编解码。
Base64 编码是一种将二进制数据转换为 ASCII 字符串的编码方式,常用于在文本环境中传输或存储二进制数据。
示例:将字符串进行 Base64 编码
const originalText = 'Hello, World!';
const encodedText = btoa(originalText);
console.log(encodedText); // 输出:SGVsbG8sIFdvcmxkIQ==
上述示例中,我们使用 btoa
函数对原始字符串 "Hello, World!"
进行 Base64 编码。编码后的结果是 "SGVsbG8sIFdvcmxkIQ=="
。
示例:将 Base64 编码的字符串进行解码
const encodedText = 'SGVsbG8sIFdvcmxkIQ==';
const decodedText = atob(encodedText);
console.log(decodedText); // 输出:Hello, World!
上述示例中,我们使用 atob
函数对经过 Base64 编码的字符串 "SGVsbG8sIFdvcmxkIQ=="
进行解码。解码后得到原始字符串 "Hello, World!"
。
需要注意的是,在浏览器环境下,这两个函数是全局对象 window
的方法;在 Node.js 环境下,则可以通过引入 'buffer'
模块来使用相应的函数。
例如,在 Node.js 环境下对字符串进行 Base64 编解码:
import { Buffer } from 'buffer';
const originalText = 'Hello, World!';
const encodedText = Buffer.from(originalText).toString('base64');
console.log(encodedText); // 输出:SGVsbG8sIFdvcmxkIQ==
const decodedText = Buffer.from(encodedText, 'base64').toString();
console.log(decodedText); // 输出:Hello, World!
这里我们使用 Buffer
对象的静态方法 from
和实例方法 toString
进行 Base64 编解码。
内容由零声教学AI助手提供,问题来源于学员提问