rust 在Tauri中,当我点击菜单项时,如何向前端发出事件

jfewjypa  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(264)

我是Tauri和Rust的新手,我尝试在点击某些菜单项时向前端发出事件

fn main() {

    Builder::default()
        .menu(build_menu())
        .on_menu_event(|event| {
            match event.menu_item_id() {
                "new" => {
                    println!("New fired");
                    // Emit event here
                }
                "save" => {
                    println!("Save fired");
                }
                "open" => {
                    println!("Open fired")
                }
                "export" => {
                    println!("Export fired");
                }
                _ => {}
            }
        })
        .run(generate_context!())
        .expect("error while running tauri application");

}

我一直在看Tauri文档和其他SO问题,但到目前为止,我只能弄清楚如何从设置中发出事件
tauri.app示例

fn main() {
  tauri::Builder::default()
    .setup(|app| {
      // `main` here is the window label; it is defined on the window creation or under `tauri.conf.json`
      // the default value is `main`. note that it must be unique
      let main_window = app.get_window("main").unwrap();

      // listen to the `event-name` (emitted on the `main` window)
      let id = main_window.listen("event-name", |event| {
        println!("got window event-name with payload {:?}", event.payload());
      });
      // unlisten to the event using the `id` returned on the `listen` function
      // an `once` API is also exposed on the `Window` struct
      main_window.unlisten(id);

      // emit the `event-name` event to the `main` window
      main_window.emit("event-name", Payload { message: "Tauri is awesome!".into() }).unwrap();
      Ok(())
    })
    .invoke_handler(tauri::generate_handler![init_process])
    .run(tauri::generate_context!())
    .expect("failed to run app");
}
laawzig2

laawzig21#

我认为你可以在on_menu_event处理程序中从事件中获取窗口,如下所示:

fn main() {
    /*create menu "What" with submenu "Hello"*/
    let hello = CustomMenuItem::new("backend_hello".to_string(), "Hello");
    let submenu = Submenu::new("What", Menu::new().add_item(hello));
    let menu = Menu::new().add_submenu(submenu);

    tauri::Builder::default()
        .menu(menu)
        .on_menu_event(|event| {
            match event.menu_item_id() {
                "backend_hello" => {
                    /*emit event for frontend here*/
                    event.window().emit("frontend_hello", Payload { message: "hello world".to_string() }).unwrap();
                }
                _ => {}
            }
        })
        .invoke_handler(tauri::generate_handler![my_custom_command])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

相关问题