前端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>
相关推荐
LuciferHuang3 小时前
震惊!三万star开源项目竟有致命Bug?
前端·javascript·debug
GISer_Jing3 小时前
前端实习总结——案例与大纲
前端·javascript
天天进步20153 小时前
前端工程化:Webpack从入门到精通
前端·webpack·node.js
姑苏洛言4 小时前
编写产品需求文档:黄历日历小程序
前端·javascript·后端
知识分享小能手4 小时前
Vue3 学习教程,从入门到精通,使用 VSCode 开发 Vue3 的详细指南(3)
前端·javascript·vue.js·学习·前端框架·vue·vue3
姑苏洛言5 小时前
搭建一款结合传统黄历功能的日历小程序
前端·javascript·后端
你的人类朋友6 小时前
🤔什么时候用BFF架构?
前端·javascript·后端
知识分享小能手6 小时前
Bootstrap 5学习教程,从入门到精通,Bootstrap 5 表单验证语法知识点及案例代码(34)
前端·javascript·学习·typescript·bootstrap·html·css3
一只小灿灿6 小时前
前端计算机视觉:使用 OpenCV.js 在浏览器中实现图像处理
前端·opencv·计算机视觉