tauri 的 plugin-store 插件怎么使用

官方文档的用法有点旧了,导致一直编译不过去。参照 github 上最新用法。

https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/store

Cargo.toml

复制代码
tauri-plugin-store = "2.0.0"

必须是 2.0.0 试过,用命令安装 版本号 "2" ,不好使

default.json

复制代码
  "permissions": [
    "store:default",
    "store:allow-get",
    "store:allow-set",
    "store:allow-save",
    "store:allow-load"
  ]

lib.rs

rust 复制代码
use serde::{Deserialize, Serialize};
use serde_json::json;
use serde_json::from_value;
use tauri_plugin_store::{ StoreExt };
use tauri::{
    AppHandle, Manager,
};


#[tauri::command]
async fn get_default_size(app: tauri::AppHandle) -> Result<(), String> {
    let monitor_opt = app.primary_monitor().map_err(|e| e.to_string())?;
    if let Some(monitor) = monitor_opt {
        // 动态获取或创建 store
        let store = app.store("config.json").map_err(|e| e.to_string())?;
        let size = monitor.size();
        let mut config = CONFIG.lock().unwrap();
        config.scale = monitor.scale_factor();
        config.screen_width = (size.width as f64 / config.scale).floor() as f64;
        config.screen_height = (size.height as f64 / config.scale).floor() as f64;

        if let Some(value) = store.get("screenInfo") {
            let prev: Config = from_value(value.clone())
                .map_err(|e| format!("Failed to deserialize: {}", e))?;
            if config.scale != prev.scale
                || prev.x == -1.0 {
                config.x = (config.screen_width / 3.0).floor() as f64;
                config.y = config.screen_height - 150.0;
                
                store.set("screenInfo", json!({
                    "screen_width": config.screen_width,
                    "screen_height": config.screen_height,
                    "scale": config.scale,
                    "x": config.x,
                    "y": config.y,
                }));
                store.save().map_err(|e| e.to_string())?;
            }
        }
    }
    Ok(())
}

App.tsx

TypeScript 复制代码
  import { Store } from '@tauri-apps/plugin-store';
  const saveStorageSize = useCallback(async (data: any) => {
    const store = await Store.load('config.json');
      // 读取
    const screenInfo: ConfigType | undefined = await store.get('screenInfo');
    if (screenInfo !== undefined) {
      if (data?.x !== undefined) {
        screenInfo.x = data.x
      }
      if (data?.y !== undefined) {
        screenInfo.y = data.y
      }
      await store.set('screenInfo', screenInfo)
      await store.save();
    }
  }, [])

生成的数据文件在:%APPDATA%\软件identifier目录下\config.json

TypeScript 复制代码
{
  "screenInfo": {
    "scale": 1.25,
    "screen_height": 864,
    "screen_width": 1536,
    "x": 513,
    "y": 750
  }
}