前言
最近看到 Tarui 都快适配移动端了,于是决定学习并实践一下该跨端框架的 PC 端实践
阅读须知
- node:v16.14.2
- pnpm 8.2.0
- rustc 1.69.0
效果图
项目搭建
pnpm create tauri-app
主要内容
实现目录选择
- 由于 Tauri 的限制,无法通过 Tarui 提供的
@tauri-apps/api/fs
模块实现文件夹选择功能。因此,可以在主进程的 Rust 代码中编写command
,并利用 Tauri 提供的@tauri-apps/api
中的invoke
方法进行交互。
- Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
- 实现
// /src/hook/useInvokeHook.js
export default function useInvokeHook() {
return {
async onDir() {
return await invoke("on_dir");
},
};
}
// 选择目录
#[tauri::command]
fn on_dir() -> Option<PathBuf> {
let file_path = tauri::api::dialog::blocking::FileDialogBuilder::new().pick_folder();
return file_path;
}
- 方法调用
const invokeHook = useInvokeHook();
const dir = await invokeHook.onDir();
console.log(dir);
实现以上方法便实现了选择指定文件夹功能
实现目录文件列表信息获取
- 实现思路将文件夹路径通过
invoke
传到rust
的 command 使用fs::read_dir
获取文件夹信息,并组装参数 - 实现
// /src/hook/useInvokeHook.js
import { FileEntry } from "@tauri-apps/api/fs";
export default function useInvokeHook() {
return {
async readDir(path: string): Promise<FileEntry[]> {
const res: string = await invoke("read_dir", { path });
const fileList = JSON.parse(res);
return fileList;
},
};
}
#[derive(Serialize)]
struct FileEntry {
name: String,
path: String,
}
//获取目录文件信息
fn get_files_in_directory(dir_path: &str) -> Result<Vec<FileEntry>, std::io::Error> {
let mut file_entries = Vec::new();
let dir = fs::read_dir(dir_path)?;
for entry in dir {
let entry = entry?;
let path = entry.path();
if path.is_file() {
let file_name = path.file_name().unwrap().to_string_lossy().into_owned();
let file_path = path.to_string_lossy().into_owned();
let file_entry = FileEntry {
name: file_name,
path: file_path,
};
file_entries.push(file_entry);
}
}
Ok(file_entries)
}
//读取目录
#[tauri::command]
fn read_dir(path: &str) -> String {
let file_entries = get_files_in_directory(path).unwrap();
let json_data = serde_json::to_string(&file_entries).unwrap();
return json_data;
}
- 方法调用
const invokeHook = useInvokeHook();
const fileList = await invokeHook.readDir(path);
console.log(fileList);
以上便是本文实现的主要内容。
效果图
后记
后续将记录实现文件读取,文件保存,创建文件,编辑器图片粘贴本地存储。
参考文档
- [tauri 官网] tauri.app/v1/guides/