Vue3 使用WebAssembly (.wasm)

1. WebAssembly 简介

WebAssembly 是一种新的编码方式,可以在现代的 Web 浏览器中运行——它是一种低级的类汇编语言,具有紧凑的二进制格式,可以接近原生的性能运行,并为诸如 C/C++、C# 和 Rust 等语言提供编译目标,以便它们可以在 Web 上运行。它也被设计为可以与 JavaScript 共存,允许两者一起工作。

2. 如何使用.wasm中的方法

(1)创建js文件引入wasm文件

const go = new Go(); // Defined in wasm_exec.js
const WASM_URL = '/wasm/login/main.wasm'; // wasm 文件地址
var wasm;
if ('instantiateStreaming' in WebAssembly) {
    WebAssembly.instantiateStreaming(fetch(WASM_URL), go.importObject).then(function (obj) {
        wasm = obj.instance;
        go.run(wasm);
    })
} else {
    fetch(WASM_URL).then(resp =>
        resp.arrayBuffer()
    ).then(bytes =>
        WebAssembly.instantiate(bytes, go.importObject).then(function (obj) {
            wasm = obj.instance;
            go.run(wasm);
        })
    )
}

// 注册导出函数
function encrypt(plaintext, publicKeyBase64) {
    return window.wasmEncrypt(plaintext, publicKeyBase64);
}

// 注册导出函数
function decrypt(cryptoText, key) {
    return window.wasmDecrypt(cryptoText, key);
}

(2)项目html中引入js文件,就可以直接使用注册导出的函数了

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link id="systemLink" rel="icon" href="" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>*********</title>
    <script src="/wasm/login/wasm_exec.js"></script>
    <script src="/wasm/login/index.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值