【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}`;
  }
};

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

相关推荐
日月云棠14 小时前
11 Spring容器整合与核心接口体系
java·后端
日月云棠14 小时前
10 AOP与动态编译源码剖析
java·后端
蓝银草同学15 小时前
新手指南:快速理清独立仓库 Java 8 多模块项目依赖并运行
前端·后端
蓝银草同学15 小时前
前端转 Java,第一篇看懂 pom.xml:Maven 依赖管理从入门到不懵
前端·后端
IT策士15 小时前
Django 从 0 到 1 打造完整电商平台:收货地址管理
后端·python·django
HjhIron15 小时前
从三件套到模块化:前端开发的底层思维
前端·后端
前端市界15 小时前
在阿里云 Docker 中管理 MySQL 8.0:常用命令与 Docker Compose 最佳实践
后端
咖啡八杯15 小时前
微信小程序人脸认证1.0迁移2.0
后端·微信小程序
甘露s15 小时前
JWT Token 机制设计演进:从单 Token 到企业级认证体系
后端·http·web
掘金码甲哥15 小时前
哈哈哈哈哈打不过我吧,没有办法我(vllm)就是这么强大!
后端