跳到正文
灵动桌面框架
Esc
本栏目菜单

Command 开发

Command 是 Rust 后端暴露给前端的 IPC 接口,每个 Command 对应一个前端可调用的函数。

定义 Command

#[tauri::command]
pub fn greet(name: &str) -> Result<String, CommandError> {
    if name.is_empty() {
        return Err(CommandError {
            code: "INVALID_INPUT".to_string(),
            message: "名称不能为空".to_string(),
        });
    }
    Ok(format!("Hello, {}! 来自 Rust 的问候!", name))
}

注入全局状态

需要访问数据库的 Command 通过 tauri::State<'_, AppState> 注入全局状态,再把 &state.db 交给 Service,并把 AppError 转成 CommandError(commands/config.rs):

#[tauri::command]
pub fn get_config(state: tauri::State<'_, AppState>, key: String) -> Result<String, CommandError> {
    ConfigService::get(&state.db, &key).map_err(|e| e.into())
}

需要应用信息(版本、数据目录)的 Command 可以直接注入 tauri::AppHandle,如 get_system_info(app: tauri::AppHandle)。

AppState 定义在 state.rs,在 lib.rs 的 setup 中注册:

app.manage(AppState::new(db));

注册 Command

在 lib.rs 中使用 generate_handler! 宏注册:

tauri::Builder::default()
    .invoke_handler(tauri::generate_handler![
        // 系统模块
        commands::system::greet,
        commands::system::get_system_info,
        // 配置模块
        commands::config::get_all_config,
        commands::config::get_config,
        commands::config::set_config,
        commands::config::delete_config,
    ])

已内置的 Commands

命令模块说明
greetsystem问候测试(保留为示例)
get_system_infosystem获取操作系统、CPU 架构、应用版本、数据目录
get_all_configconfig查询所有配置(不含已软删除)
get_configconfig查询单个配置
set_configconfig设置配置(不存在则新增)
delete_configconfig软删除配置

完整的参数与返回值见 Commands 列表。

新增 Command 步骤

  1. 在 commands/ 目录编写函数,标记 #[tauri::command];新文件需在 commands/mod.rs 中 pub mod 声明
  2. 返回 Result<T, CommandError>,Service 返回的 AppError 用 .map_err(|e| e.into()) 转换
  3. 在 lib.rs 的 generate_handler! 中注册
  4. 权限:build.rs 只调用 tauri_build::build(),未声明应用命令清单,应用自定义 Command 无需在 capabilities/default.json 中加权限;该文件管理的是 core:* 与插件权限,调用插件新能力时才需要补
  5. 在前端 src/lib/api/ 编写调用封装(如 configApi),并在 src/lib/api/index.ts 中导出;类型放到 src/types/