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

Store 存储插件

Store 插件提供简单的键值持久化存储,适合保存用户设置、偏好等小型数据。

框架已注册插件(tauri_plugin_store::Builder::default().build())并授予 store:default 权限,但模板前端目前没有调用它:设置页的配置项走的是 SQLite(configApi → get_all_config / set_config 等 Command),Zustand 的 useSettingsStore 也只是内存状态。需要轻量键值存储时按下文直接使用。

基本用法

import { Store } from '@tauri-apps/plugin-store'

// 创建/打开 store(相对路径,存放在应用数据目录)
const store = await Store.load('settings.json')

// 写入
await store.set('theme', 'dark')
await store.set('fontSize', 14)

// 读取
const theme = await store.get<string>('theme')
const fontSize = await store.get<number>('fontSize')

// 删除
await store.delete('theme')

// 立即保存到磁盘(默认已自动保存,见注意事项)
await store.save()

// 清空所有
await store.clear()

在 Zustand 中使用

import { create } from 'zustand'
import { Store } from '@tauri-apps/plugin-store'

interface SettingsState {
  theme: string
  fontSize: number
  setTheme: (theme: string) => Promise<void>
  load: () => Promise<void>
}

export const useSettingsStore = create<SettingsState>((set) => ({
  theme: 'light',
  fontSize: 14,

  setTheme: async (theme) => {
    const store = await Store.load('settings.json')
    await store.set('theme', theme)
    await store.save()
    set({ theme })
  },

  load: async () => {
    const store = await Store.load('settings.json')
    set({
      theme: (await store.get<string>('theme')) ?? 'light',
      fontSize: (await store.get<number>('fontSize')) ?? 14,
    })
  },
}))

框架已有同名的 src/store/settings.ts(字段是 language、closeBehavior),照此改造时注意别覆盖现有字段。

注意事项

  • Store 文件存储在应用数据目录(app_data_dir,Windows 为 %APPDATA%\com.agilefr.tauri\,macOS 为 ~/Library/Application Support/com.agilefr.tauri/),与框架的 SQLite 数据库(app.db,开发版为 dev-app.db)同目录
  • 适合存储小型配置数据,大量数据请使用 SQLite
  • 默认开启自动保存:每次修改后防抖 100ms 写盘。需要立即落盘(如紧接着退出 / 重启)时再手动调用 save();Store.load('x.json', { defaults: {}, autoSave: false }) 可关闭自动保存