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

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

相关推荐
代码老y30 分钟前
ASP.NET Core 高并发万字攻防战:架构设计、性能优化与生产实践
后端·性能优化·asp.net
武子康5 小时前
Java-80 深入浅出 RPC Dubbo 动态服务降级:从雪崩防护到配置中心秒级生效
java·分布式·后端·spring·微服务·rpc·dubbo
舒一笑6 小时前
我的开源项目-PandaCoder迎来史诗级大更新啦
后端·程序员·intellij idea
@昵称不存在7 小时前
Flask input 和datalist结合
后端·python·flask
zhuyasen7 小时前
Go 分布式任务和定时任务太难?sasynq 让异步任务从未如此简单
后端·go
东林牧之8 小时前
Django+celery异步:拿来即用,可移植性高
后端·python·django
超浪的晨9 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
AntBlack9 小时前
从小不学好 ,影刀 + ddddocr 实现图片验证码认证自动化
后端·python·计算机视觉
Pomelo_刘金9 小时前
Clean Architecture 整洁架构:借一只闹钟讲明白「整洁架构」的来龙去脉
后端·架构·rust
双力臂4049 小时前
Spring Boot 单元测试进阶:JUnit5 + Mock测试与切片测试实战及覆盖率报告生成
java·spring boot·后端·单元测试