前端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/[email protected]/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/[email protected]/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>
相关推荐
hao_wujing5 分钟前
Web 连接和跟踪
服务器·前端·javascript
前端小白从0开始7 分钟前
前端基础知识CSS系列 - 04(隐藏页面元素的方式和区别)
前端·css
想不到耶7 分钟前
Vue3轮播图组件,当前轮播区域有当前图和左右两边图,两边图各显示一半,支持点击跳转和手动滑动切换
开发语言·前端·javascript
萌萌哒草头将军1 小时前
🚀🚀🚀尤雨溪:Vite 和 JavaScript 工具的未来
前端·vue.js·vuex
Fly-ping1 小时前
【前端】cookie和web stroage(localStorage,sessionStorage)的使用方法及区别
前端
我家媳妇儿萌哒哒2 小时前
el-upload 点击上传按钮前先判断条件满足再弹选择文件框
前端·javascript·vue.js
天天向上10242 小时前
el-tree按照用户勾选的顺序记录节点
前端·javascript·vue.js
sha虫剂2 小时前
如何用div手写一个富文本编辑器(contenteditable=“true“)
前端·vue.js·typescript
咔咔库奇2 小时前
深入探索 Vue 3 Fragments:从原理到实战的全方位指南
前端·javascript·vue.js