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

news/2024/4/19 11:16:06/文章来源:https://blog.csdn.net/qq_44472790/article/details/129184770

一.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>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_73200.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

类与对象(this 关键字、构造器)

目录一、面向对象二、类与对象三、对象内存图四、成员变量和局部变量区别五、this关键字六、构造器/构造方法一、面向对象 一种编程思想:也就是说我们要以何种思路&#xff0c;解决问题&#xff0c;以何种形式组织代码 当解决一个问题的时候&#xff0c;面向对象会把事物抽象成…

分享app的测试技巧

前言 今天笔者想和大家来唠唠app测试&#xff0c;现在的app有非常的多&#xff0c;这些app都是需要经过测试之后才能发布到应用市场中&#xff0c;app已经成为了我们日常生活中不可或缺的一部分了&#xff0c;但它的功能必须强大&#xff0c;才能受到消费者的重视&#xff0c;…

已解决from cryptography.hazmat.backends import default_backend导包错误

已解决Python连接FTPS抛出异常&#xff1a;CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography. The next release of cryptography (40.0) will be the last to support …

pyaudio声卡信息中hostApi是什么意思?

hostApi是声卡驱动协议&#xff0c;声卡驱动模式&#xff0c;有如下很多类。下面的类型是网上找的PortAudio的类&#xff0c;不不确定是不是python的。typedef enum PaHostApiTypeId{paInDevelopment0, /* use while developing support for a new host API */paDirectSound1,p…

深度学习之“制作自定义数据”--torch.utils.data.DataLoader重写构造方法。

深度学习之“制作自定义数据”–torch.utils.data.DataLoader重写构造方法。 前言&#xff1a; ​ 本文讲述重写torch.utils.data.DataLoader类的构造方法&#xff0c;对自定义图片制作类似MNIST数据集格式&#xff08;image, label&#xff09;&#xff0c;用于自己的Pytorc…

推荐系统从入门到入门(3)——基于MapReuduce与Spark的分布式推荐系统构建

本系列博客总结了不同框架、不同算法、不同界面的推荐系统&#xff0c;完整阅读需要大量时间&#xff08;又臭又长&#xff09;&#xff0c;建议根据目录选择需要的内容查看&#xff0c;欢迎讨论与指出问题。 目录 系列文章梗概 系列文章目录 三、MapReduce 1.MapReduce详…

【视频】海康摄像头、NVR网络协议简介

1、软硬件整体架构 2、涉及的网络协议 3、协议简介 3.1 海康私有协议 设备发现SADP:进行设备的发现、激活、修改网络参数、忘记密码等; SDK:4200、系统平台的接入前端设备,协议不对外开放,但对外提供接口库; ISAPI:Intelligent Security API(智能安全API),基于HTTP传输…

2023新的一年软件测试还值得学习吗?

最近因为疫情等各种原因&#xff0c;大厂裁员&#xff0c;失业等等频频受到关注。不解释&#xff0c;确实存在&#xff0c;各行各业都很难&#xff0c;但是&#xff0c;说软件测试行业不吃香&#xff0c;我还真不认同&#xff08;不是为培训机构说好话&#xff0c;大环境不好&a…

Odoo丨Odoo框架源码研读三:异常处理与定制化开发

Odoo丨Odoo框架源码研读三&#xff1a;异常处理与定制化开发 Odoo源码研读的第三期内容&#xff1a;异常处理与定制化开发。 *异常处理* Odoo中的Exception是对Python内置异常做了继承和封装&#xff0c;设定了自己核心的几个Exception。 而对异常的处理和Python内置异常的…

Spring 之bean的生命周期

文章目录IOCBean的生命周期运行结果实例演示实体类实例化前后置代码初始化的前后置代码application.xml总结今天我们来聊一下Spring Bean的生命周期&#xff0c;这是一个非常重要的问题&#xff0c;Spring Bean的生命周期也是比较复杂的。IOC IOC&#xff0c;控制反转概念需要…

Flutter+【三棵树】

定义 在Flutter中和Widgets一起协同工作的还有另外两个伙伴&#xff1a;Elements和RenderObjects&#xff1b;由于它们都是有着树形结构&#xff0c;所以经常会称它们为三棵树。 这三棵树分别是&#xff1a;Widget、Element、RenderObject Widget树&#xff1a;寄存烘托内容…

SigmaPlot科学绘图工具:ROC曲线分析及AUC组间差异的显著性分析

目的 初步使用SigmaPlot科学绘图工具&#xff1b;进行ROC曲线绘制并分析检验变量AUC组间差异性是否显著 软件下载及安装 SigmaPlot下载安装按照这个教程即可&#xff1a;https://www.hhkxxw.com/24799.html 快速通道&#xff1a;SigmaPlot下载链接&#xff1a;百度网盘链接…

DC220V冲击继电器RCJ-3

系列型号 RCJ-2型冲击继电器&#xff1b; RCJ-2/48VDC冲击继电器 RCJ-2/110VDC冲击继电器 RCJ-2/220VDC冲击继电器 RCJ-2/100VAC冲击继电器 RCJ-2/127VAC冲击继电器 RCJ-2/220VAC冲击继电器 RCJ-3/220VAC冲击继电器 RCJ-3型冲击继电器 RCJ-3/127VAC冲击继电器 RCJ-3/100VAC冲…

FastCGI sent in stderr: "PHP message: PHP Fatal error

服务器php7.2卸载安装7.4之后,打开网站一直无法访问,查看nginx错误日志发现一直报这个错误:2023/02/23 11:12:55 [error] 4735#0: *21 FastCGI sent in stderr: &#xff02;PHP message: PHP Fatal error: Uncaught ReflectionException: Class translator does not exist in …

Python四大主题之一【 Web】 编程框架

目前Python的网络编程框架已经多达几十个&#xff0c;逐个学习它们显然不现实。但这些框架在系统架构和运行环境中有很多共通之处&#xff0c;本文带领读者学习基于Python网络框架开发的常用知识,及目前的4种主流Python网络框架&#xff1a;Django、Tornado、Flask、Twisted。 …

100%BIM学员的疑惑:不会CAD可以学Revit吗?

在新一轮科技创新和产业变革中&#xff0c;信息化与建筑业的融合发展已成为建筑业发展的方向&#xff0c;将对建筑业发展带来战略性和全局性的影响。 建筑业是传统产业&#xff0c;推动建筑业科技创新&#xff0c;加快推进信息化发展&#xff0c;激发创新活力&#xff0c;培育…

web客户端-websocket

1、websocket简介 WebSocket是HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议。 WebSocket使得客户端和服务器之间的数据交换变得更加简单&#xff0c;允许服务端主动向客户端推送数据。在WebSocket API中&#xff0c;浏览器和服务器只需要完成一次握手&#xff0c…

python3.11.2安装 + pycharm安装

下载 &#xff1a;https://www.python.org/ 2.双击下载的软件&#xff1a; 3.进入安装界面 下一步&#xff0c;点击 是 上一步点击后就看到如下&#xff1a; 安装成功了&#xff0c;接下来检测一下&#xff1a;cmd 安装pycharm PyCharm是一种Python IDE&#xff08;Integr…

Apifox-比postman更优秀的接口自动化测试平台

一、Apifox介绍 Apifox 是 API 文档、API 调试、API Mock、API 自动化测试一体化协作平台&#xff0c;定位 Postman Swagger Mock JMeter。通过一套系统、一份数据&#xff0c;解决多个系统之间的数据同步问题。只要定义好 API 文档&#xff0c;API 调试、API 数据 Mock、A…

你真的需要文档管理软件吗?

什么是文档管理软件&#xff1f; 文档管理软件 (DMS) 是一种数字解决方案&#xff0c;可帮助组织处理、捕获、存储、管理和跟踪文档。 通过严格管理您的关键业务信息&#xff0c;您可以开发以稳定、可预测、可衡量的方式启动、执行和完成的流程。 如果没有功能齐全的文档管理软…