前端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>
相关推荐
mCell2 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip2 小时前
Node.js 子进程:child_process
前端·javascript
excel5 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel6 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼8 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping8 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙9 小时前
[译] Composition in CSS
前端·css
白水清风9 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix9 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278009 小时前
new、原型和原型链浅析
前端·javascript