当前位置: 首页 > 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交互…...

Linux | 网络通信 | http协议介绍 | cookie策略讲解

文章目录url统一资源定位符http协议介绍GET vs POSThttp状态码http常见headercookie session上篇博客定制了一个协议&#xff0c;该协议用来进行简单的计算&#xff0c;其包含了数据的序列化和反序列化&#xff0c;编码和解码的定制&#xff0c;并且该协议基于TCP通信&#xf…...

招投标系统简介 招投标系统源码 java招投标系统 招投标系统功能设计

项目说明 随着公司的快速发展&#xff0c;企业人员和经营规模不断壮大&#xff0c;公司对内部招采管理的提升提出了更高的要求。在企业里建立一个公平、公开、公正的采购环境&#xff0c;最大限度控制采购成本至关重要。符合国家电子招投标法律法规及相关规范&#xff0c;以及…...

winapi获取和修改camera raw界面元素数据

camera raw 界面如下&#xff1a; 需求就是根据 windows api 来操作界面右边的色温、色调、曝光等属性&#xff0c;进而对图片进行调色。根据 spy 捕获的窗口信息&#xff0c;理论上是可以拿到并修改值的。 根据 class 可以先拿到窗口句柄&#xff1a; #define CAMERA_RAW_CLA…...

C++问答汇总_2023自用

C是一种通用编程语言&#xff0c;具有高级抽象、强类型和编译性能等特点。C语言具有许多特性&#xff0c;包括面向对象编程、模板、多态、运算符重载等等。它广泛应用于各种领域&#xff0c;如系统软件、嵌入式系统、游戏开发、科学计算等等。 1、C11相对于C98的新特性&#xf…...

IDA 实战--(2)熟悉工具

布局介绍 软件启动后会 有几个选项&#xff0c;一般直接选择Go 即可 之后的工作台布局如下 开始分析 分析的第一个&#xff0c;将PE 文件拖入工作区 刚开始接触&#xff0c;我们先保持默认选项&#xff0c;其它选项后面会详细讲解&#xff0c;点击OK 后&#xff0c;等待分析…...

Deep Unsupervised Learning using Nonequilibrium Thermodynamics论文翻译学习

Deep Unsupervised Learning using Nonequilibrium Thermodynamics Author: Jascha Sohl-Dickstein Link: http://proceedings.mlr.press/v37/sohl-dickstein15.pdf Score: ⭐️⭐️⭐️⭐️⭐️ Status: Done Type: Academic Journal 备注: 首篇扩散模型论文 A central prob…...

使用Autoware标定工具包联合标定相机和激光雷达

前面文章介绍了&#xff0c;安装autoware标定工具包、ros驱动usb相机、robosense-16线激光雷达的使用&#xff0c;本文记录使用Autoware标定工具包联合标定相机和激光雷达的过程。1.ros驱动相机&#xff0c;启动相机&#xff1b;启动激光雷达2.联合录制bag包rosbag record -a 参…...

了解线程安全

线程安全是多线程的重点和难点。 线程安全概念 线程安全&#xff1a;在多线程的各种随机调度顺序下&#xff0c;代码没有bug&#xff0c;都能够符合预期的方式来执行&#xff0c;此时认为线程安全 线程不安全&#xff1a;如果在多线程随机调度下代码出现bug&#xff0c;此时…...

【git】git版本控制

目录 1.在合适的位置打开bush,创建仓库 2.检查&#xff1a;跳转到当前文件夹&#xff0c;显示当前文件夹的相对路径 3.初始化 4.创建一个文本文件readme.txt 5.手动向readme文件中添加一些内容 6.把文件添加到暂存区 7.把文件提交到git仓库 8.手动修改readme.txt文件 9.查看当前…...

模电学习7. 三极管特性曲线与静态工作点

模电学习7. 三极管特性曲线与静态工作点一、三极管的伏安特性曲线1. 三极管的伏安特性曲线2. 三极管的静态工作点二、合适的静态工作点选择1. 合适静态工作点条件2. 静态工作点的确定三、使用立创EDA仿真查看静态工作点1. 搭建如下图所示测试电路2. 点击菜单仿真、仿真设置3. 运…...