Tauri 調(diào)用指令

2023-09-19 19:56 更新

Tauri 為您的前端開發(fā)提供了其他系統(tǒng)原生功能。 我們將其稱作指令,這使得您可以從 JavaScript 前端調(diào)用由 Rust 編寫的函數(shù)。 由此,您可以使用性能飛快的 Rust 代碼處理繁重的任務(wù)或系統(tǒng)調(diào)用。

以下是一個(gè)簡單示例:

src-tauri/src/main.rs

#[tauri::command]
fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}

一個(gè)指令等于一個(gè)普通的 Rust 函數(shù),只是還加上了 #[tauri::command] 宏來讓其與您的 JavaScript 環(huán)境交互。

最后,我們需要讓 Tauri 知悉您剛創(chuàng)建的指令才能讓其調(diào)用。 我們需要使用 .invoke_handler() 函數(shù)及 Generate_handler![] 宏來注冊指令:

src-tauri/src/main.rs

fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

現(xiàn)在您的前端可以調(diào)用剛注冊的指令了!

我們通常會推薦使用 @tauri-apps/api 包,但由于本指南至此還沒有使用打包工具,所以您需要在 tauri.conf.json 文件中啟用 withGlobalTauri 選項(xiàng)。

tauri.conf.json

{
"build": {
"beforeBuildCommand": "",
"beforeDevCommand": "",
"devPath": "../ui",
"distDir": "../ui",
"withGlobalTauri": true
},

此選項(xiàng)會將已打包版本的 API 函數(shù)注入到您的前端中。

您現(xiàn)在可以修改您的 index.html 文件來調(diào)用您的指令:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1 id="header">Welcome from Tauri!</h1>
<script>
// access the pre-bundled global API functions
const { invoke } = window.__TAURI__.tauri

// now we can call our Command!
// You will see "Welcome from Tauri" replaced
// by "Hello, World!"!
invoke('greet', { name: 'World' })
// `invoke` returns a Promise
.then((response) => {
window.header.innerHTML = response
})
</script>
</body>
</html>
提示
若您想要了解更多有關(guān) Rust 和 JavaScript 之間通信的信息,請參閱 Tauri 進(jìn)程間通信指南。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號