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

vue3-vuex持久化实现

vue3-vuex持久化实现

  • 一、背景描述
  • 二、实现思路
    • 1.定义数据结构
    • 2.存值
    • 3.取值
    • 4.清空
  • 三、具体代码
    • 1.定义插件
    • 2.使用插件
  • 四、最终效果

一、背景描述

有时候我们可能需要在vuex中存储一些静态数据,比如一些下拉选项的字典数据。这种数据基本很少会变化,所以我们可能希望将其存储起来,这样就减少了请求的数量。
但是在每个位置都进行存储,好像是在做重复的逻辑,所以我们可以考虑将这个功能提取出来,作为一个插件使用。
注意:建议不要滥用持久化存储,因为这可能导致你不能获取到最新的数据,只建议在一些长期不会变化的数据中使用。

二、实现思路

做到持久化存储,那就要在页面销毁之前将值存到storage中,页面初始化的时候,再将值取到vuex中进行数据初始化

1.定义数据结构

我们首先要规定哪些值需要存储,因为我们没必要持久化存储大部分的vuex数据,所以没必要进行全量存储。
我这里将数据结构定义为数组:

const storageItem = [{storageType: 'local', // 存储类型:local或者sessionstorageKey: 'name', // 存储的keystorageValue: () => Store.getters.getName || '', // 需要存储的值,也可以用 () => Store.state.name 这种形式storeMutations: 'SET_NAME' // vuex设置值时的mutations,用于页面刷新完成之后初始化vuex}
]

每多一个需要持久化存储的内容,就增加一个元素即可。

2.存值

在页面销毁前存值我们可以直接在window的beforeunload回调中进行即可

window.addEventListener('beforeunload', () => {storageItem.forEach(item => {const storage =item.storageType === 'session' ? sessionStorage : localStoragestorage.setItem(item.storageKey, item.storageValue())})})

也可以在vue组件的onUnmounted回调中进行存储,但是这样就需要你在vue组件中执行这个逻辑了。当然你也可以考虑将逻辑封装为hooks。

3.取值

在页面渲染前从storage中取到值,并且初始化vuex。
有一点可能要注意,我们从后端获取一些全局数据时,一般会在routerBeforeEach中进行接口调用。所以不建议在window的load回调中调用。我们执行初始化尽量在routerBeforeEach之前执行,这样我们就可以判断vuex如果存在值,就不用再调用接口了。
我这里在main.js中调用插件时执行:

storageItem.forEach(item => {const storage =item.storageType === 'session' ? sessionStorage : localStoragelet storageValue = storage.getItem(item.storageKey)try {storageValue = JSON.parse(storageValue as string)} catch {}if (storageValue) {if (item.storeMutations) {Store.commit(item.storeMutations, storageValue)}}})

4.清空

我们可以提供一个清空的方法,便于某些时候清空所有的存储(如果担心数据时效性,可以设置一个时间,超出这个时间段之后就全部清空)

  storageItem.forEach(item => {const storage =item.storageType === 'session' ? sessionStorage : localStoragestorage.removeItem(item.storageKey)})

三、具体代码

1.定义插件

新建一个storeStorage.js

import Store from '@/store'
/*** 统一移除存储的vuex数据*/
export const removeStoreStorage = () => {storageItem.forEach(item => {const storage =item.storageType === 'session' ? sessionStorage : localStoragestorage.removeItem(item.storageKey)})
}
// 持久化存储相应vuex数据
const storageItem = [{storageType: 'local', // 存储类型:local或者sessionstorageKey: 'name', // 存储的keystorageValue: () => Store.getters.getName || '', // 需要存储的值storeMutations: 'SET_NAME' // vuex设置值时的mutations,用于页面刷新完成之后初始化vuex}
]
export default {install() {this.getStoreStorage()this.setStoreStorage()},/*** 页面销毁前,存储数据*/setStoreStorage() {window.addEventListener('beforeunload', () => {storageItem.forEach(item => {const storage =item.storageType === 'session' ? sessionStorage : localStoragestorage.setItem(item.storageKey, item.storageValue())})})},/*** 页面刷新时,重新加载存储的vuex数据*/getStoreStorage() {storageItem.forEach(item => {const storage =item.storageType === 'session' ? sessionStorage : localStoragelet storageValue = storage.getItem(item.storageKey)try {storageValue = JSON.parse(storageValue as string)} catch {}if (storageValue) {if (item.storeMutations) {Store.commit(item.storeMutations, storageValue)}}})}
}

2.使用插件

main.js中引入,并使用

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import storeStorage from '@/util/storeStorage'
import store from './store'
const app = createApp(App)
app.use(store).use(router).use(storeStorage).mount('#app')

其中vuex中index.js定义:

import { createStore } from 'vuex'export default createStore({state: {name: '',age: ''},getters: {getName: state => state.name,getAge: state => state.age},mutations: {SET_NAME(state, name) {state.name = name},SET_AGE(state, age) {state.age = age}},actions: {},modules: {}
})

四、最终效果

app.vue

<template><input type="text" v-model="$store.state.name"/>
</template><style lang="scss">
#app {color: #2c3e50;
}
</style>
<script setup lang="ts">
</script>

在这里插入图片描述
输入内容再刷新页面就会发现值被缓存了。

注:插件、routerBeforeEach和window.load执行顺序

router.beforeEach((to, from, next) => {console.log('routerBeforeEach')next()
})
window.addEventListener('load', () => {console.log('load')
})

插件中的部分代码

 /*** 页面刷新时,重新加载存储的vuex数据*/getStoreStorage() {storageItem.forEach(item => {const storage =item.storageType === 'session' ? sessionStorage : localStoragelet storageValue = storage.getItem(item.storageKey)try {storageValue = JSON.parse(storageValue as string)} catch {}if (storageValue) {if (item.storeMutations) {Store.commit(item.storeMutations, storageValue)}}})console.log('getStoreStorage')}

执行结果:
在这里插入图片描述

http://www.lryc.cn/news/151719.html

相关文章:

  • 详解 SpringMVC 的 @RequestMapping 注解
  • 类的静态成员变量 static member
  • MVSNet (pytorch版) 搭建环境 运行dtu数据集重建 实操教程(图文并茂、超详细)
  • Linux系统Ubuntu以非root用户身份操作Docker的方法
  • m4s格式转换mp4
  • SQL sever中库管理
  • 模板方法模式简介
  • 自动化运维工具-------Ansible(超详细)
  • 计算机毕设 基于生成对抗网络的照片上色动态算法设计与实现 - 深度学习 opencv python
  • Citespace、vosviewer、R语言的文献计量学 、SCI
  • linux操作系统的权限的深入学习
  • LeetCode——三数之和(中等)
  • SpringMVC使用
  • 【css】css奇数、偶数、指定数选择器:
  • 三维数据Ply格式介绍与读取
  • 内存管理方式
  • 文心一言接入Promptulate,开发复杂LLM应用程序
  • TDengine函数大全-聚合函数
  • DRM全解析 —— ADD_FB(2)
  • windows下docker compose方式挂载数据卷volume遇到的问题
  • TCP三次握手四次挥手总结
  • 【0901作业】QTday3 对话框、发布软件、事件处理机制,使用文件相关操作完成记事本的保存功能、处理键盘事件完成圆形的移动
  • mysql数据库运行sql:datetime(0) NULL DEFAULT NULL报错【杭州多测师_王sir】
  • 手撕二叉平衡树
  • 超图嵌入论文阅读1:对偶机制非均匀超网络嵌入
  • Qt xml解析之QXmlStreamReader
  • Selenium基础 — CSS选择器定位大全
  • vue3中keep-alive的使用及结合transition使用
  • 【提示工程】询问GPT返回Json结构数据
  • CSS水平垂直居中方案