前端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>
相关推荐
wkj0012 小时前
vue中 js-cookie 用法
前端·javascript·vue.js
GoldKey6 小时前
gcc 源码阅读---语法树
linux·前端·windows
Xf3n1an7 小时前
html语法
前端·html
张拭心7 小时前
亚马逊 AI IDE Kiro “狙击”Cursor?实测心得
前端·ai编程
烛阴7 小时前
为什么你的Python项目总是混乱?层级包构建全解析
前端·python
@大迁世界8 小时前
React 及其生态新闻 — 2025年6月
前端·javascript·react.js·前端框架·ecmascript
红尘散仙8 小时前
Rust 终端 UI 开发新玩法:用 Ratatui Kit 轻松打造高颜值 CLI
前端·后端·rust
新酱爱学习9 小时前
前端海报生成的几种方式:从 Canvas 到 Skyline
前端·javascript·微信小程序
袁煦丞9 小时前
把纸堆变数据流!Paperless-ngx让文件管理像打游戏一样爽:cpolar内网穿透实验室第539个成功挑战
前端·程序员·远程工作
慧慧吖@9 小时前
关于两种网络攻击方式XSS和CSRF
前端·xss·csrf