スポンサーリンク
以下の3ファイルが、GUIの編集とイベント処理に必要になる
index.htmlに、buttonを追加。IDをMyNewButtonとする。
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="stylesheet" href="styles.css" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Tauri App</title> <script type="module" src="/main.js" defer></script> <style> .logo.vanilla:hover { filter: drop-shadow(0 0 2em #ffe21c); } </style> </head> <body> <div class="container"> <h1>Welcome to Tauri!</h1> <div class="row"> <a href="https://tauri.app" target="_blank"> <img src="/assets/tauri.svg" class="logo tauri" alt="Tauri logo" /> </a> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank" > <img src="/assets/javascript.svg" class="logo vanilla" alt="JavaScript logo" /> </a> </div> <p>Click on the Tauri logo to learn more about the framework</p> <form class="row" id="greet-form"> <input id="greet-input" placeholder="Enter a name..." /> <button type="submit">Greet</button> </form> <p id="greet-msg"></p> <p></p> <button id="MyNewButton" type="button">新しいボタン</button> </div> </body> </html>
Rust側の関数 my_rust_function を呼び出すJavascriptを記述。myvalueは引数。
const { invoke } = window.__TAURI__.tauri; let greetInputEl; let greetMsgEl; async function greet() { // Learn more about Tauri commands at https://tauri.app/v1/guides/features/command greetMsgEl.textContent = await invoke("greet", { name: greetInputEl.value }); } window.addEventListener("DOMContentLoaded", () => { greetInputEl = document.querySelector("#greet-input"); greetMsgEl = document.querySelector("#greet-msg"); document.querySelector("#greet-form").addEventListener("submit", (e) => { e.preventDefault(); greet(); });
document.getElementById("MyNewButton").addEventListener("click",async (e) => { invoke("my_rust_function", { myvalue: 55555 }); });
});
// Prevents additional console window on Windows in release, DO NOT REMOVE!! #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // Learn more about Tauri commands at https://tauri.app/v1/guides/features/command #[tauri::command] fn greet(name: &str) -> String { format!("Hello, {}! You've been greeted from Rust!", name) }
#[tauri::command] fn my_rust_function(myvalue: i32){ // カレントディレクトリへテキストファイルを作成 std::fs::write("my_rust_function.txt", format!("myvalue: {}", myvalue)).unwrap(); }
fn main() { tauri::Builder::default() .invoke_handler(tauri::generate_handler![greet]) .invoke_handler(tauri::generate_handler![my_rust_function]) .run(tauri::generate_context!()) .expect("error while running tauri application"); }
my_rust_function.txtが生成される。