Appearance
Store 存储插件
Store 插件提供简单的键值持久化存储,适合保存用户设置、偏好等小型数据。
基本用法
typescript
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 中使用
typescript
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,
})
},
}))注意事项
- Store 文件存储在应用数据目录(
AppData/Application Support) - 适合存储小型配置数据,大量数据请使用 SQLite
- 每次
set后需要调用save()才会持久化到磁盘