当前位置: 首页 > news >正文

vue3全家桶之vuex和pinia持久化存储基础(二)

一.vuex数据持久化存储

这里使用的是vuex@4.1.0版本,和之前的vuex@3一样,数据持久化存储方案也使用 vuex-persistedstate,版本是最新的安装版本,当前可下载依赖包版本4.1.0,接下来在vue3项中安装和使用:

安装vuex-persistedstate

npm i vuex-persistedstate --save 或者 yarn add vuex-persistedstate

使用vuex-persistedstate

src/stores/index.ts

import { createStore } from 'vuex'
import moduleTest from './modules/moduleTest'
import createPersistedState from 'vuex-persistedstate'import vuexPersistTest from './vuexPersistTest'
// 创建一个新的 store 实例
export default createStore({state () {return {sum: 0,hell: 'hello world'}},mutations: {// 负责修改state中的count值sumMutations (state, newVal) {state.sum += newVal}},actions: {sumActions ({ commit }, params) {// 触发mutations中的countMutations函数并传递参数setTimeout(()=>{commit("sumMutations", params)},300)}},getters: {getSum: state => state.sum},modules: {moduleTest,vuexPersistTest},plugins: [  createPersistedState({storage: sessionStorage,paths: ["vuexPersistTest.sum","vuexPersistTest.nameList","sum","hell"],key: "createPersistedState"}), createPersistedState({storage: localStorage,paths: ["vuexPersistTest.count"],key: "createPersistedState"}) ],
})

在main.js使用store

import { createApp } from 'vue'
import store from './stores'import App from './App.vue'
import router from './router'import './assets/main.css'createApp(App).use(store).use(router).mount('#app')

简单分析createPersistedState

plugins: [  // 可以多组createPersistedState实例使用createPersistedState({storage: sessionStorage,// 模块vuexPersistTest中有sum 和 nameList字段paths: ["vuexPersistTest.sum","vuexPersistTest.nameList","sum","hell"],key: "createPersistedState"}), createPersistedState({// 存储类型storage: localStorage,// 需要持久化的state属性paths: ["vuexPersistTest.count"],// 存储的keykey: "createPersistedState"}) ],

createPersistedState可配置属性:

key <String>:用于存储持久状态的密钥。默认为vuex。
paths <Array>:任何路径的数组,以部分保留状态。如果未给出路径,则完整状态将保留。如果给定一个空数组,则不会保留任何状态。必须使用点表示法指定路径。如果使用模块,请包括模块名称。例如:“ auth.user”默认为undefined。
reducer <Function>:将根据给定路径调用以减少状态持久化的函数。默认值包括这些值。
subscriber <Function>:一个用于设置突变订阅的函数。默认为store => handler => store.subscribe(handler)。
storage <Object>:代替(或结合)getState和setState。默认为localStorage。
getState <Function>:将被调用以恢复先前持久状态的功能。默认使用storage。
setState <Function>:将被调用以保持给定状态的函数。默认使用storage。
filter <Function>:一个将被调用以过滤setState最终将在存储中触发的任何突变的函数。默认为() => true。
overwrite <Boolean>:补液时,是否getState直接用输出结果覆盖现有状态,而不是用合并两个对象deepmerge。默认为false。
arrayMerger <Function>:补充状态时合并数组的功能。默认为function (store, saved) { return saved }(保存状态替换提供状态)。
rehydrated <Function>:补液完成后将被调用的函数。当您使用Nuxt.js时,该功能非常有用,持久化状态的恢复是异步发生的。默认为store => {}
fetchBeforeUse <Boolean>:一个布尔值,指示在使用插件之前是否应从存储中获取状态。默认为false。
assertStorage <Function>:确保插件可用的可重写功能,会在插件初始化时触发。默认情况下,是在给定的Storage实例上执行Write-Delete操作。请注意,默认行为可能会引发错误(如DOMException: QuotaExceededError)

store/modules/vuexPersistTest.ts模块作为定义state属性用来测试持久化

export default {  state: { sum: 0,count: 100,nameList: ["张三","李四"]},  mutations: { updateSum (state:any,newVal:number) {state.sum = newVal},updateCount (state:any,newVal:number) {state.count = newVal},updateNameList (state:any, newVal:string[]) {state.nameList = newVal},},  actions: {  },  modules: {  }
}

在views/test.vue 测试,运行页面操作状态属性修改

<script setup lang="ts">import { computed,ref } from 'vue'import { useStore} from 'vuex'const {commit,dispatch,state,getters,actions} = useStore();// 数据持久化const getPersistTestSum = computed(()=> state.vuexPersistTest.count)const updatePersistTestSum = () => {commit('updateSum',state.vuexPersistTest.sum+1)}const updatePersistTestCount = () => {commit('updateCount',state.vuexPersistTest.count+1)}const updatePersistTestName = () => {commit('updateNameList',['更新数据中...'])}
</script><template><main><div style="margin-bottom:20px"><button @click="updatePersistTestSum">改变sum</button>{{ state.vuexPersistTest.sum }}<br><button @click="updatePersistTestCount">改变count</button>{{ state.vuexPersistTest.count }}<br><button @click="updatePersistTestName">改变nameList</button>{{ state.vuexPersistTest.nameList }}<br></main>
</template>

二.pinia数据持久化存储

pinia持久化官方推荐使用使用pinia-plugin-persist插件处理持久化存储问题,具体参考:

https://seb-l.github.io/pinia-plugin-persist/#install

安装pinia-plugin-persist

npm install pinia-plugin-persist 或者 yarn add pinia-plugin-persist

在入口文件main.ts引入

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist'import App from './App.vue'
import router from './router'const pinia = createPinia()
pinia?.use(piniaPersist)createApp(App).use(pinia).use(store).use(router).mount('#app')

src/stores/piniaPersistTest.ts 新建一个测试模块

import { defineStore } from "pinia";
import { ref } from "vue";
import Cookies from "js-cookie";// 对象写法
export const usePersistTest1 = defineStore("storePersist", {state: () => {return {firstName: "S",lastName: "L",accessToken: "xxxxxxxxxxxxx",count: 100,};},actions: {setToken(value: string) {this.accessToken = value;},},persist: {// 开启持久存储enabled: true,// 指定哪些state的key需要进行持久存储// storage默认是 sessionStorage存储// paths需要持久存储的keystrategies: [{ storage: localStorage, paths: ["accessToken"] },{ storage: sessionStorage, paths: ["firstName", "lastName"] },],},
});// 函数写法
export const usePersistTest = defineStore("storePersist",() => {const firstName = ref("S");const lastName = ref("L");const accessToken = ref("XXXXXXXX");const count = ref(100);return {firstName,lastName,accessToken,count,};},{persist: {// 开启持久存储 开启 enabled 之后,默认会对整个 Store 的 state 内容进行 sessionStorage 储存enabled: true,// 自定义存储的 key,默认是 store.$id//  key: "custom storageKey",// 指定哪些state的key需要进行持久存储// storage默认是 sessionStorage存储// paths需要持久存储的keystrategies: [{ storage: sessionStorage, paths: ["firstName", "lastName"] },{ storage: localStorage, paths: ["accessToken"] },],},}
);const cookiesStorage: any = {setItem(key:string, state:any): any {const myState = JSON.parse(state)return Cookies.set(key, myState[key], { expires: 3 })},getItem(key:string): string {return JSON.stringify({[key]: Cookies.get(key),})},removeItem(key) { },clear() { }}export const usePersistTestCokie = defineStore("persistTestCokie", () => {const username = ref("王者之巅")const counter = ref(100)const accessToken = ref("xxx")return { username, counter, accessToken }
}, {persist: {enabled: true,strategies: [{storage: cookiesStorage,key: 'username',paths: ['username']},{storage: cookiesStorage,key: 'counter',paths: ['counter']},{storage: cookiesStorage,key: 'accessToken',paths: ['accessToken']},],}
})

src/views/piniaTest.vue组建测试

<script setup lang="ts">
import { RouterLink, RouterView } from "vue-router";
import { usePersistTest,usePersistTestCokie } from "./stores/piniaPersistTest";const persistStore = usePersistTest();
const persistTestCokie = usePersistTestCokie()const changePersist = () => {persistStore.count++;persistStore.lastName = "测试name";persistStore.accessToken = "测试accessToken";persistStore.firstName = "测试第一name";
};
</script><template><button @click="changeCountHanlder">测试pinia</button>{{ counterStore.count }} 和 {{ counterStore.sum }}<br /><button @click="changePersist">持久存储</button>count:{{ persistStore.count }}<br>lastName:{{ persistStore.lastName }}<br>accessToken:{{ persistStore.accessToken }}<br>firstName:{{ persistStore.firstName }}<br>CokieSave:<button @click="persistTestCokie.accessToken='ddddfdf3434ffdsfsfs33'">存储cokie</button>username:{{ persistTestCokie.username }} counter:{{ persistTestCokie.counter }} accessToken:{{ persistTestCokie.accessToken }}
</template>

相关文章:

vue3全家桶之vuex和pinia持久化存储基础(二)

一.vuex数据持久化存储 这里使用的是vuex4.1.0版本,和之前的vuex3一样,数据持久化存储方案也使用 vuex-persistedstate,版本是最新的安装版本,当前可下载依赖包版本4.1.0&#xff0c;接下来在vue3项中安装和使用&#xff1a; 安装vuex-persistedstate npm i vuex-persisteds…...

LAMP架构与搭建论坛

目录 1、LAMP架构简述 2、各组件作用 3、构建LAMP平台 1.编译安装Apache httpd服务 2.编译安装mysql 3.编译安装php 4.搭建一个论坛 1、LAMP架构简述 LAMP架构是目前成熟的企业网站应用模式之一&#xff0c;指的是协同工作的一整台系统和相关软件&#xff0c;能够提供动…...

代码随想录 || 回溯算法93 78 90

Day2493.复原IP地址力扣题目链接给定一个只包含数字的字符串&#xff0c;复原它并返回所有可能的 IP 地址格式。有效的 IP 地址 正好由四个整数&#xff08;每个整数位于 0 到 255 之间组成&#xff0c;且不能含有前导 0&#xff09;&#xff0c;整数之间用 . 分隔。例如&#…...

界面组件Kendo UI for Angular——让网格数据信息显示更全面

Kendo UI致力于新的开发&#xff0c;来满足不断变化的需求&#xff0c;通过React框架的Kendo UI JavaScript封装来支持React Javascript框架。Kendo UI for Angular是专用于Angular开发的专业级Angular组件&#xff0c;telerik致力于提供纯粹的高性能Angular UI组件&#xff0c…...

【Linux】进程状态|优先级|进程切换|环境变量

文章目录1. 运行队列和运行状态2. 进程状态3. 两种特殊的进程僵尸进程孤儿进程4. 进程优先级5. 进程切换进程特性进程切换6. 环境变量的基本概念7. PATH环境变量8. 设置和获取环境变量9. 命令行参数1. 运行队列和运行状态 &#x1f495; 运行队列&#xff1a; 进程是如何在CP…...

合宙Air780E|FTP|内网穿透|命令测试|LuatOS-SOC接口|官方demo|学习(18):FTP命令及应用

1、FTP服务器准备 本机为win11系统&#xff0c;利用IIS搭建FTP服务器。 搭建方式可参考博文&#xff1a;windows系统搭建FTP服务器教程 windows系统搭建FTP服务器教程_程序员路遥的博客-CSDN博客_windows服务器安装ftp 设置完成后&#xff0c;测试FTP&#xff08;已正常访问…...

大规模 IoT 边缘容器集群管理的几种架构-4-Kubeedge

前文回顾 大规模 IoT 边缘容器集群管理的几种架构-0-边缘容器及架构简介大规模 IoT 边缘容器集群管理的几种架构-1-RancherK3s大规模 IoT 边缘容器集群管理的几种架构-2-HashiCorp 解决方案 Nomad大规模 IoT 边缘容器集群管理的几种架构-3-Portainer &#x1f4da;️Reference…...

Spring底层核心原理解析

Spring简介 ClassPathXmlApplicationContext context new classPathXmlApplicationContext("spring.xml"); UserService userService (UserService) context.getBean("userService"); userService.test();上面一段代码是我们开始学习spring时看到的&…...

OpenStack手动分布式部署Glance【Queens版】

目录 Glance简介 1、登录数据库配置&#xff08;在controller执行&#xff09; 1.1登录数据库 1.2数据库里创建glance 1.3授权对glance数据库的正确访问 1.4退出数据库 1.5创建glance用户密码为000000 1.6增加admin角色 1.7创建glance服务 1.8创建镜像服务API端点 2、安装gla…...

谈一谈你对View的认识和View的工作流程

都2023年了&#xff0c;不会还有人不知道什么是View吧&#xff0c;不会吧&#xff0c;不会吧。按我以往的面试经验来看&#xff0c;View被问到的概率不比Activity低多少哦&#xff0c;个人感觉View在Android中的重要性也和Activity不相上下&#xff0c;所以这篇文章将介绍下Vie…...

Redis集群的脑裂问题

集群脑裂导致数据丢失怎么办&#xff1f; 什么是脑裂&#xff1f; 先来理解集群的脑裂现象&#xff0c;这就好比一个人有两个大脑&#xff0c;那么到底受谁控制呢&#xff1f; 那么在 Redis 中&#xff0c;集群脑裂产生数据丢失的现象是怎样的呢&#xff1f; 在 Redis 主从架…...

互斥信号+任务临界创建+任务锁

普通信号量 1、信号量概念 2、创建信号量函数 3、互斥信号量 创建互斥信号量函数 等待信号量函数 释放互斥信号量 4、创建任务临界区 5、任务锁 任务上锁函数 ​编辑 任务结束函数 效果 普通信号量 1、信号量概念 信号量像是一种上锁机制&#xff0c;代码必须获…...

Elasticsearch7.8.0版本进阶——文档搜索

目录一、文档搜索的概述二、倒排索引不可变的优点三、倒排索引不可变的优点一、文档搜索的概述 早期的全文检索会为整个文档集合建立一个很大的倒排索引并将其写入到磁盘。 一旦新的索引就绪&#xff0c;旧的就会被其替换&#xff0c;这样最近的变化便可以被检索到。倒排索引被…...

spring security权限问题

org.springframework.boot spring-boot-starter-security 引入jar extends WebSecurityConfigurerAdapter 用来配置登陆和权限 configure(HttpSecurity http) 覆盖这个方法 //配置授权相关的 .authorizeRequests () //任何请求 .anyRequest() //要求授权后可以访问 .authen…...

mysql 8.0.22安装

mysql8.0.22安装1. 配置my.ini2. 添加环境变量3. 安装mysql3.1 mysql初始化3.2 安装mysql服务3.3 启动mysql服务4. 连接数据库修改连接数据库的密码前提&#xff1a;已经从官网下载mysql8.0.22安装包并解压&#xff08;下载地址&#xff1a;https://dev.mysql.com/downloads/in…...

Mysql系列:Mysql5.7编译安装

系统环境&#xff1a;Centos7 1&#xff1a;下载mysql源码包 https://dev.mysql.com/downloads/mysql/5.7.html downloads 选择MySQL Community Server>source_code>Generic Linux (Architecture Independent), Compressed TAR Archive -> 选择需要的mysql版本&…...

设备树(配合LED驱动说明)

目录 一、起源 二、基本组成 三、基本语法 四、特殊节点 4.1 根节点 4.2 /memory 4.3 /chosen 4.4 /cpus 多核CPU支持 五、常用属性 5.1 phandle 5.2 地址 --------------- 重要 5.3 compatible --------------- 重要 5.4 中断 --------------- 重要 5.5 …...

(二十六)大白话如何从底层原理解决生产的Too many connections故障?

今天我们继续讲解昨天的那个案例背景&#xff0c;其实就是经典的Too many connections故障&#xff0c;他的核心就是linux的文件句柄限制&#xff0c;导致了MySQL的最大连接数被限制&#xff0c;那么今天来讲讲怎么解决这个问题。 其实核心就是一行命令&#xff1a; ulimit -H…...

ASEMI高压MOS管60R380参数,60R380特征,60R380应用

编辑-Z ASEMI高压MOS管60R380参数&#xff1a; 型号&#xff1a;60R380 漏极-源极电压&#xff08;VDS&#xff09;&#xff1a;600V 栅源电压&#xff08;VGS&#xff09;&#xff1a;20V 漏极电流&#xff08;ID&#xff09;&#xff1a;11A 功耗&#xff08;PD&#x…...

Python期末试卷

《Python程序设计基础》期末试题 班级 学号 姓名 一&#xff0e;选择题(须知:答案写到下方的表格中,其它一律无效.每题2分&#xff0c;共40分) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 1.在Python交互…...

OpenClaw从入门到应用——频道:IRC

通过OpenClaw实现副业收入&#xff1a;《OpenClaw赚钱实录&#xff1a;从“养龙虾“到可持续变现的实践指南》 Quick start 在 ~/.openclaw/openclaw.json 中启用 IRC 配置。至少设置以下内容&#xff1a; theme{"theme":{"light":"min-light"…...

GCC扩展语法在嵌入式开发中的高效应用

1. GCC扩展语法深度解析在嵌入式开发领域&#xff0c;GCC编译器因其强大的功能和灵活的扩展特性而广受欢迎。作为一名长期从事嵌入式系统开发的工程师&#xff0c;我发现掌握GCC的扩展语法能显著提升代码效率和可维护性。今天我将分享几个在实际项目中特别实用的GCC扩展语法特性…...

响应 (接上文)

在我们前⾯的代码例⼦中&#xff0c;都已经设置了响应数据,Http响应结果可以是数据,也可以是静态⻚⾯,也可 以针对响应设置状态码,Header信息等.返回静态⻚⾯创建前端⻚⾯index.html(注意路径)html代码如下:<!DOCTYPE html> <html lang"en"> <head>…...

《YOLOv11 实战:从入门到深度优化》002、环境搭建:从零配置YOLOv11开发与训练环境

002、环境搭建&#xff1a;从零配置YOLOv11开发与训练环境 昨天深夜调试一个边缘设备上的推理异常&#xff0c;问题最终定位到CUDA版本和torch不匹配——这种环境配置埋下的坑&#xff0c;往往比算法本身更难排查。今天咱们就老老实实把YOLOv11的环境从头搭一遍&#xff0c;这份…...

突破流放之路BD构建瓶颈:PoeCharm汉化版全功能技术指南

突破流放之路BD构建瓶颈&#xff1a;PoeCharm汉化版全功能技术指南 【免费下载链接】PoeCharm Path of Building Chinese version 项目地址: https://gitcode.com/gh_mirrors/po/PoeCharm 在流放之路复杂的角色构建系统中&#xff0c;如何让每一份资源投入都转化为实实在…...

Workbench网格划分实战指南:从基础到进阶技巧

1. Workbench网格划分入门&#xff1a;为什么选择它&#xff1f; 如果你是第一次接触Workbench的网格划分功能&#xff0c;可能会好奇为什么这么多工程师选择它。简单来说&#xff0c;Workbench提供了一个可视化操作界面&#xff0c;让复杂的网格划分变得像搭积木一样直观。我刚…...

引领RFID电子标签打印新时代,打造标识打印系统新标杆

在当今快速发展的数字化时代&#xff0c;RFID电子标签凭借其非接触式数据读取、大容量存储以及高可靠性等优势&#xff0c;在众多领域得到了广泛应用。而HCreateLabelView 标识打印系统作为上海平宇码创科技自主研发的核心产品&#xff0c;紧密贴合这一趋势&#xff0c;为RFID电…...

C++ lambda 捕获机制剖析

C lambda 捕获机制剖析 在现代C编程中&#xff0c;lambda表达式因其简洁性和灵活性成为开发者常用的工具之一。lambda的核心特性之一是其捕获机制&#xff0c;它允许在匿名函数内部访问外部变量。理解捕获机制不仅能提升代码效率&#xff0c;还能避免潜在的内存和逻辑错误。本…...

QMCDecode终极解决方案:突破QQ音乐加密格式限制的完全指南

QMCDecode终极解决方案&#xff1a;突破QQ音乐加密格式限制的完全指南 【免费下载链接】QMCDecode QQ音乐QMC格式转换为普通格式(qmcflac转flac&#xff0c;qmc0,qmc3转mp3, mflac,mflac0等转flac)&#xff0c;仅支持macOS&#xff0c;可自动识别到QQ音乐下载目录&#xff0c;默…...

新手友好:借助快马平台的免费token轻松迈出AI应用开发第一步

作为一名刚接触AI开发的新手&#xff0c;我最近在InsCode(快马)平台上完成了一个文本摘要生成器的项目&#xff0c;整个过程非常顺畅。这个平台对初学者特别友好&#xff0c;尤其是提供了免费token&#xff0c;让我们可以零成本体验AI开发的乐趣。 理解token的概念 刚开始我对…...