Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

Rust-Wasm 向 Vue3 传递函数,并绑定到dom事件上

本人想通过由 Rust 语言 写的事件函数经过编译成 Webassembly

然后给 Vue3 的事件绑定函数使用

Rust 语言使用的包为 wasm-bindgen
编译工具为 wasm-pack
编译命令:$ wasm-pack build --target web

Cargo.toml:

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2.55"
gloo = "0.2.0"


[dependencies.web-sys]
version = "0.3.4"
features = [
  'Document',
  'Element',
#  'CssStyleDeclaration',
  'HtmlElement',
#  'HtmlParagraphElement',
#  'HtmlTextAreaElement',
#  'Node',
  'Window',
  'console',
  'KeyboardEvent',
]

Rust 代码:

#[wasm_bindgen]
pub fn hidesibebar(e:web_sys::KeyboardEvent){
        console_log!("ok1");
        console_log!("{}",e.key())
        // if e.ctrl_key() && e.alt_key(){
        //     console_log!("true");
        // }
}
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console)]
    fn log(s:&str);
}

macro_rules! console_log {
    ($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
}

Vue3 代码

<template>
      <div class="TagsContainer" @keydown="hidesibebar">
          <ul>
              <li>123</li>
              <li>123</li>
          </ul>
      </div>
</template>

<script>
import "keyevent/keyevent_bg.wasm"
import init,{hidesibebar} from "keyevent/keyevent.js"
import {defineComponent} from "vue"
export default defineComponent({
    async setup(){
        // async function run() {
        //     await init()
        // }
       let wasm = await init()
        // console.log(wasm);
    //    let hidesibebar = wasm.hidesibebar
    //    let hidesibebar = hidesibebar

       return {hidesibebar}
    }

})
</script>
<div>
    <Suspense>
    <tagscontainer></tagscontainer>
    </Suspense>
<div/>
//...
//...
//...

我使用了 Vite 来运行了这个项目

wasm 文件要被线上初始化,所以我引入了这个文件 keyevent/keyevent_bg.wasm

我从它的外包 JS 文件keyevent/keyevent.js引入 init 方法与 Rust函数 编译出来的函数

并要使用 async setup 来异步初始化 init

且这个组件被使用要使用 Suspense 包裹

可从 Vite playground借鉴

但是在 Rust 代码中 hidesibebar 函数中

如果我不写对 事件参数e:web_sys::KeyboardEvent调用

只有 console_log!("ok"); 是可以被绑定上,

但我是想使用这个事件参数,不知道怎么解决,希望有解决方案


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...