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,接下来在vue3项中安装和使用: 安装vuex-persistedstate npm i vuex-persisteds…...

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

代码随想录 || 回溯算法93 78 90
Day2493.复原IP地址力扣题目链接给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。有效的 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 . 分隔。例如&#…...

界面组件Kendo UI for Angular——让网格数据信息显示更全面
Kendo UI致力于新的开发,来满足不断变化的需求,通过React框架的Kendo UI JavaScript封装来支持React Javascript框架。Kendo UI for Angular是专用于Angular开发的专业级Angular组件,telerik致力于提供纯粹的高性能Angular UI组件,…...

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

合宙Air780E|FTP|内网穿透|命令测试|LuatOS-SOC接口|官方demo|学习(18):FTP命令及应用
1、FTP服务器准备 本机为win11系统,利用IIS搭建FTP服务器。 搭建方式可参考博文:windows系统搭建FTP服务器教程 windows系统搭建FTP服务器教程_程序员路遥的博客-CSDN博客_windows服务器安装ftp 设置完成后,测试FTP(已正常访问…...

大规模 IoT 边缘容器集群管理的几种架构-4-Kubeedge
前文回顾 大规模 IoT 边缘容器集群管理的几种架构-0-边缘容器及架构简介大规模 IoT 边缘容器集群管理的几种架构-1-RancherK3s大规模 IoT 边缘容器集群管理的几种架构-2-HashiCorp 解决方案 Nomad大规模 IoT 边缘容器集群管理的几种架构-3-Portainer 📚️Reference…...
Spring底层核心原理解析
Spring简介 ClassPathXmlApplicationContext context new classPathXmlApplicationContext("spring.xml"); UserService userService (UserService) context.getBean("userService"); userService.test();上面一段代码是我们开始学习spring时看到的&…...

OpenStack手动分布式部署Glance【Queens版】
目录 Glance简介 1、登录数据库配置(在controller执行) 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年了,不会还有人不知道什么是View吧,不会吧,不会吧。按我以往的面试经验来看,View被问到的概率不比Activity低多少哦,个人感觉View在Android中的重要性也和Activity不相上下,所以这篇文章将介绍下Vie…...
Redis集群的脑裂问题
集群脑裂导致数据丢失怎么办? 什么是脑裂? 先来理解集群的脑裂现象,这就好比一个人有两个大脑,那么到底受谁控制呢? 那么在 Redis 中,集群脑裂产生数据丢失的现象是怎样的呢? 在 Redis 主从架…...

互斥信号+任务临界创建+任务锁
普通信号量 1、信号量概念 2、创建信号量函数 3、互斥信号量 创建互斥信号量函数 等待信号量函数 释放互斥信号量 4、创建任务临界区 5、任务锁 任务上锁函数 编辑 任务结束函数 效果 普通信号量 1、信号量概念 信号量像是一种上锁机制,代码必须获…...
Elasticsearch7.8.0版本进阶——文档搜索
目录一、文档搜索的概述二、倒排索引不可变的优点三、倒排索引不可变的优点一、文档搜索的概述 早期的全文检索会为整个文档集合建立一个很大的倒排索引并将其写入到磁盘。 一旦新的索引就绪,旧的就会被其替换,这样最近的变化便可以被检索到。倒排索引被…...
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. 连接数据库修改连接数据库的密码前提:已经从官网下载mysql8.0.22安装包并解压(下载地址:https://dev.mysql.com/downloads/in…...
Mysql系列:Mysql5.7编译安装
系统环境:Centos7 1:下载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故障?
今天我们继续讲解昨天的那个案例背景,其实就是经典的Too many connections故障,他的核心就是linux的文件句柄限制,导致了MySQL的最大连接数被限制,那么今天来讲讲怎么解决这个问题。 其实核心就是一行命令: ulimit -H…...

ASEMI高压MOS管60R380参数,60R380特征,60R380应用
编辑-Z ASEMI高压MOS管60R380参数: 型号:60R380 漏极-源极电压(VDS):600V 栅源电压(VGS):20V 漏极电流(ID):11A 功耗(PD&#x…...
Python期末试卷
《Python程序设计基础》期末试题 班级 学号 姓名 一.选择题(须知:答案写到下方的表格中,其它一律无效.每题2分,共40分) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 1.在Python交互…...
【Go】3、Go语言进阶与依赖管理
前言 本系列文章参考自稀土掘金上的 【字节内部课】公开课,做自我学习总结整理。 Go语言并发编程 Go语言原生支持并发编程,它的核心机制是 Goroutine 协程、Channel 通道,并基于CSP(Communicating Sequential Processes࿰…...

html-<abbr> 缩写或首字母缩略词
定义与作用 <abbr> 标签用于表示缩写或首字母缩略词,它可以帮助用户更好地理解缩写的含义,尤其是对于那些不熟悉该缩写的用户。 title 属性的内容提供了缩写的详细说明。当用户将鼠标悬停在缩写上时,会显示一个提示框。 示例&#x…...

【JVM】Java虚拟机(二)——垃圾回收
目录 一、如何判断对象可以回收 (一)引用计数法 (二)可达性分析算法 二、垃圾回收算法 (一)标记清除 (二)标记整理 (三)复制 (四ÿ…...

并发编程 - go版
1.并发编程基础概念 进程和线程 A. 进程是程序在操作系统中的一次执行过程,系统进行资源分配和调度的一个独立单位。B. 线程是进程的一个执行实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。C.一个进程可以创建和撤销多个线程;同一个进程中…...
c# 局部函数 定义、功能与示例
C# 局部函数:定义、功能与示例 1. 定义与功能 局部函数(Local Function)是嵌套在另一个方法内部的私有方法,仅在包含它的方法内可见。 • 作用:封装仅用于当前方法的逻辑,避免污染类作用域,提升…...
字符串哈希+KMP
P10468 兔子与兔子 #include<bits/stdc.h> using namespace std; typedef unsigned long long ull; const int N 1000010; ull a[N], pw[N]; int n; ull gethash(int l, int r){return a[r] - a[l - 1] * pw[r - l 1]; } signed main(){ios::sync_with_stdio(false), …...
boost::filesystem::path文件路径使用详解和示例
boost::filesystem::path 是 Boost 库中用于跨平台操作文件路径的类,封装了路径的拼接、分割、提取、判断等常用功能。下面是对它的使用详解,包括常用接口与完整示例。 1. 引入头文件与命名空间 #include <boost/filesystem.hpp> namespace fs b…...

欢乐熊大话蓝牙知识17:多连接 BLE 怎么设计服务不会乱?分层思维来救场!
多连接 BLE 怎么设计服务不会乱?分层思维来救场! 作者按: 你是不是也遇到过 BLE 多连接时,调试现场像网吧“掉线风暴”? 温度传感器连上了,心率带丢了;一边 OTA 更新,一边通知卡壳。…...

Springboot 高校报修与互助平台小程序
一、前言 随着我国经济迅速发展,人们对手机的需求越来越大,各种手机软件也都在被广泛应用,但是对于手机进行数据信息管理,对于手机的各种软件也是备受用户的喜爱,高校报修与互助平台小程序被用户普遍使用,为…...

JUC并发编程(二)Monitor/自旋/轻量级/锁膨胀/wait/notify/锁消除
目录 一 基础 1 概念 2 卖票问题 3 转账问题 二 锁机制与优化策略 0 Monitor 1 轻量级锁 2 锁膨胀 3 自旋 4 偏向锁 5 锁消除 6 wait /notify 7 sleep与wait的对比 8 join原理 一 基础 1 概念 临界区 一段代码块内如果存在对共享资源的多线程读写操作…...