tauri基本学习.md

发布时间 2023-06-08 09:49:44作者: nsfoxer

Tauri基本学习

项目基本介绍

构建新项目:

npm create tauri-app@latest

cd 项目/
npm install
npm run tauri dev

文件目录

nsfoxer@nsfoxer-pc~/T/Study $ tree -L 1
.
├── dist
├── index.html
├── node_modules
├── package.json
├── package-lock.json
├── public
├── README.md
├── src         # 前端界面代码
├── src-tauri   # rust后端代码 
├── tsconfig.json
├── tsconfig.node.json
└── vite.config.ts

6 directories, 7 files


├── src-tauri    
│   ├── build.rs
│   ├── Cargo.lock
│   ├── Cargo.toml
│   ├── icons
│   ├── src
│   ├── target
│   └── tauri.conf.json  # tauri的配置

前端调用后端代码

前端调用后端

基本调用

// 前端
import { useState } from "react";
import { invoke } from "@tauri-apps/api/tauri";
import "./App.css";

function App() {
   const [time, setTime] = useState('');

    // 异步调用
   async function get_path(e) {
        const r = await invoke("get_path") as string;
        setTime(r);
       // 手动阻止事件
        e.preventDefault();
   }

  return (
    <div>
        <button onClick={get_path}>点我</button>
        <p> {time} </p>
    </div>
  );
}

export default App;
// 后端代码
// 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 get_path() -> String{
    format!("这里是rust的响应")
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![greet, get_path]) // 同时这里也需要添加上
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

参数传递

  1. 前端参数使用驼峰式的key,使用json传递
  2. 后端使用snake_case形式接收参数
  3. 参数可以是任何类型,但是必须实现serde::Deserialize
  4. 返回值可以是任何类型,但是必须实现serde::Deserialize
async function get_path() {
    const r = await invoke("get_path", {currentValue: value}) as number;
    setValue(r);
}
#[tauri::command]
fn get_path(current_value: u32) -> u32{
    current_value + 10
}

错误处理

  1. 后端返回 Result,前端需要promise错误捕获。
  2. 错误类型也许要实现serde::Serialize
  3. 由于大部分错误类型并未实现serde::Serialize,所以需要自定义错误类型。
async function file() {
   try {
    invoke("open_file");
   } catch (e) {
    console.error(e);
   }

}
#[derive(Debug, thiserror::Error)]
enum Error {
    #[error(transparent)]
    Io(#[from] std::io::Error)
}

impl serde::Serialize for Error {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: serde::Serializer {
        serializer.serialize_str(self.to_string().as_ref())
    }
}

#[tauri::command]
fn open_file() -> Result<(), Error> {
    fs::File::open("/tmp/sds")?;
    Ok(())
}

获取window

#[tauri::command]
fn window_label(window: tauri::Window) -> String {
    window.label().to_owned()
}