【Tauri2.0教程(十二)】tauri store插件的使用

前言

本文参考官方文章编写。

store 插件,顾名思义持久化所开发应用的某些数据。比如我现在要做一个应用,需要应用支持切换主题,每次打开APP,需要记住用户之前选择的主题是什么。这时候就需要将选择的主题存储下来。

如果不使用插件,在程序安装目录放置一个配置文件,每次程序启动读取匹配文件中的内容也是可以的。 但是官方既然提供了插件,我们看一下插件是如何使用的。

安装

bash 复制代码
npm run tauri add store

权限配置

src-tauri\capabilities\default.json文件中添加如下权限:

json 复制代码
{
  "permissions": [
    "store:default",
  ]
}

目前新版,安装完插件以后,权限信息是会自动添加进去的,如果没有添加,可以像上面这样手动添加。

使用说明

vue 复制代码
<template>
  <component :is="'style'" v-if="dynamicCss" v-html="dynamicCss"></component>
  <ThemeSelector msg="Readora"/>
</template>

<script setup>
import ThemeSelector from './components/ThemeSelector.vue'
import {onBeforeMount, onMounted, ref} from 'vue';
import {invoke} from '@tauri-apps/api/core';
// 1. 引入方法
import {load} from '@tauri-apps/plugin-store';
import {warn, debug, trace, info, error, attachConsole} from '@tauri-apps/plugin-log';
attachConsole()
const dynamicCss = ref('');
const themeLoadError = ref('');
let store = undefined;
let currentTheme = ref('weread-dark');

onBeforeMount(async () => {
  // 2. 获取store,如果没有settings.json会自动创建
  store = await load('settings.json', {});
  // 3. 读取配置
  const storeTheme = await store.get('currentTheme')
  if (storeTheme) {
    currentTheme.value = storeTheme;
  } else {
    // 4. 写入配置
    await store.set('currentTheme', currentTheme.value)
  }

  // Apply the stored theme
  await applyTheme();
});

// 初始化主题,根据主题名称通过rust加载主题文件夹下面的主题
const applyTheme = async () => {
  try {
    dynamicCss.value = await invoke('load_theme_css', {themeName: currentTheme.value});
    // 更新主题
    await store.set('currentTheme', currentTheme.value)
    info("currentTheme name:[" + currentTheme.value + ']')
  } catch (error) {
    console.error('Error loading theme:', error);
    dynamicCss.value = ''; // Clear CSS on error
    themeLoadError.value = `Error applying theme: ${error}`;
  }
};

上述代码是我在写一个主题切换功能时的代码,包含了读取和写入配置等功能。

相关推荐
考虑考虑2 小时前
Excel导入时产生特殊字符处理
java·后端·java ee
IT_陈寒2 小时前
Redis的DEL命令竟然没删掉数据?我踩的这个坑你得知道
前端·人工智能·后端
用户938515635072 小时前
Docker + Nginx + Node.js:从“我的电脑能跑,你的电脑跑不了”到一键部署
后端·nginx·docker
陆枫Larry2 小时前
两步验证(2FA )到底是什么?
后端
JavaGuide2 小时前
我用 Claude Code/ZCode+GLM-5.3 从零做了一款 Agent 游戏!
前端·后端
程序员清风2 小时前
专业再升级!程序员专属显示器明基RD280UG上手实测!
java·后端·面试
刘立军3 小时前
RESTful 与契约优先:规范接口定义,统一接口设计范式
后端·架构·ai编程
JavaGuide4 小时前
GitHub 4.5 万+ Star!GitNexus 把代码仓库变成了 Claude Code / Codex 能查询的知识图谱
后端·ai编程
子兮曰4 小时前
DeepSeek Harness 架构深潜:一个把 Agent 运行时做成纯插件树的开源 Harness
前端·后端·deepseek
子兮曰5 小时前
AI Agent 完整入门指南:从 LLM 到生产落地的 30+ 个核心概念
前端·后端·agent