前端Base64 编码和解码的使用方法

使用 Base64 类从 'js-base64' 库进行 Base64 编码和解码

一、安装 'js-base64'库

vue: 使用 npm 或 yarn 包管理器来安装'js-base64' 库

c 复制代码
npm install --save js-base64

原生: 通过

c 复制代码
<script src="https://cdn.jsdelivr.net/npm/js-base64@3.7.2/base64.min.js"></script>

二、导入'js-base64'库

vue:

导入 Base64 类:

c 复制代码
import { Base64 } from 'js-base64';

或者:

c 复制代码
import { encode, decode } from 'js-base64';

三、在页面中使用

vue:

Base64 编码的使用示例:

c 复制代码
import { Base64 } from 'js-base64';

const stringToEncode = 'Hello, World!'; // 要进行 Base64 编码的字符串
const encodedString = Base64.encode(stringToEncode); // 进行 Base64 编码
console.log(encodedString); // 输出:SGVsbG8sIFdvcmxkIQ==

Base64 解码的使用示例:

c 复制代码
import { Base64 } from 'js-base64';

const base64String = 'SGVsbG8sIFdvcmxkIQ=='; // Base64 编码的字符串
const decodedString = Base64.decode(base64String); // 进行 Base64 解码
console.log(decodedString); // 输出:Hello, World!

或者,导入 encode 和 decode 函数:

Base64 编码的使用示例:

c 复制代码
import { encode } from 'js-base64';

const stringToEncode = 'Hello, World!'; // 要进行 Base64 编码的字符串
const encodedString = encode(stringToEncode); // 进行 Base64 编码
console.log(encodedString); // 输出:SGVsbG8sIFdvcmxkIQ==

Base64 解码的使用示例:

c 复制代码
import { decode } from 'js-base64';

const base64String = 'SGVsbG8sIFdvcmxkIQ=='; // Base64 编码的字符串
const decodedString = decode(base64String); // 进行 Base64 解码
console.log(decodedString); // 输出:Hello, World!

原生:

使用 'js-base64' 进行 Base64 编码和解码:

c 复制代码
<!DOCTYPE html>
<html>
<head>
  <title>Base64 Example</title>
  <script src="https://cdn.jsdelivr.net/npm/js-base64@3.7.2/base64.min.js"></script>
</head>
<body>
  <script>
    const stringToEncode = 'Hello, World!'; // 要进行 Base64 编码的字符串
    const encodedString = Base64.encode(stringToEncode); // 进行 Base64 编码
    console.log(encodedString); // 输出:SGVsbG8sIFdvcmxkIQ==

    const base64String = 'SGVsbG8sIFdvcmxkIQ=='; // Base64 编码的字符串
    const decodedString = Base64.decode(base64String); // 进行 Base64 解码
    console.log(decodedString); // 输出:Hello, World!
  </script>
</body>
</html>
相关推荐
PineappleCoder4 小时前
性能数据别再瞎轮询了!PerformanceObserver 异步捕获 LCP/CLS,不卡主线程
前端·性能优化
PineappleCoder4 小时前
告别字体闪烁 / 首屏卡顿!preload 让关键资源 “高优先级” 提前到
前端·性能优化
m0_471199635 小时前
【vue】通俗详解package-lock文件的作用
前端·javascript·vue.js
GIS之路5 小时前
GDAL 读取KML数据
前端
今天不要写bug5 小时前
vue项目基于vue-cropper实现图片裁剪与图片压缩
前端·javascript·vue.js·typescript
用户47949283569156 小时前
记住这张时间线图,你再也不会乱用 useEffect / useLayoutEffect
前端·react.js
咬人喵喵6 小时前
14 类圣诞核心 SVG 交互方案拆解(附案例 + 资源)
开发语言·前端·javascript
问君能有几多愁~6 小时前
C++ 日志实现
java·前端·c++
咬人喵喵6 小时前
CSS 盒子模型:万物皆是盒子
前端·css