vuex数据可持久化(项目)


vuex数据可持久化-对于刷新也需要保留状态的需要同步到本地存储

Vuex实现数据持久化,解决浏览器刷新数据丢失问题

vuex的 store 中的数据是保存在运行内存中的,当页面刷新时,页面会重新加载 vue 实例,vuex 里面的数据就会被重新赋值,这样就会出现页面刷新vuex中的数据丢失的问题。 如何解决浏览器刷新数据丢失问题呢?

方法一:全局监听,页面刷新的时候将 store 里 state 的值存到 sessionStorage 中,然后从sessionStorage 中获取,再赋值给 store ,并移除 sessionStorage 中的数据。在 app.vue 中添加以下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
created() {
window.addEventListener('beforeunload',()=>{
sessionStorage.setItem('list', JSON.stringify(this.$store.state))
})

try{
sessionStorage.getItem('list') && this.$store.replaceState(Object.assign({},this.$store.state,JSON.parse(sessionStorage.getItem('list'))))
}catch(err) {
console.log(err);
}

sessionStorage.removeItem("list");
}

注意!!! storage 只能存储字符串的数据,对于 JS 中常用的数组或对象不能直接存储。但我们可以通过JSON 对象提供的 parse 和 stringify 方法将其他数据类型转化成字符串,再存储到storage中就可以了。

方法二:安装 vuex-persistedstate 插件

1
2
3
4
5
6
7
8
9
1. npm install vuex-persistedstate -S //安装插件
2. 在 store/index.js 文件中添加以下代码:
import persistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
state:{},
getters:{},
...
plugins: [persistedState()] //添加插件
})

注意!!! vuex-persistedstate 默认使用 localStorage 来存储数据,若要实现无痕浏览该如何实现呢?

这时候就需要使用 sessionStorage 进行存储,修改 plugins 中的代码

1
2
3
plugins: [
persistedState({ storage: window.sessionStorage })
]
注意事项:
  1. storage为存储方式,可选值为localStorage、sessionStorage和cookies;
  2. localStorage和sessionStorage两种存储方式可以采用上述代码中的写法,若想采用cookies坐位数据存储方式,则需要另外一种写法;
  3. render接收一个函数,返回值为一个对象;返回的对象中的键值对既是要持久化存储的数据;
  4. 若想持久化存储部分数据,请在return的对象中采用key:value键值对的方式进行数据存储,render函数中的参数既为state对象。

方案三:vuex-persist

1
2
3
4
安装插件
yarn add vuex-persist
// 或
npm install --save vuex-persist

使用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import Vuex from "vuex";
// 引入插件
import VuexPersistence from "vuex-persist";

Vue.use(Vuex);
// 初始化
const state = {
userName:'admin'
};
const mutations = {};
const actions = {};
// 创建实例
const vuexPersisted = new VuexPersistence({
storage: window.sessionStorage,
render:state=>({
userName:state.userName
// 或
...state
})
});

const store = new Vuex.Store({
state,
actions,
mutations,
// 数据持久化设置
plugins:[vuexPersisted]
});

export default store;

Vuex实现数据持久化,解决浏览器刷新数据丢失问题
Vuex数据持久化存储

比vuex更好用的Pinia,pinia模块化如何实现?pinia如何实现数据持久化?

pinia模块化如何实现?

pinia相比vuex没有modules,那么如何实现模块化呢?
在复杂项目中,不可能把多个模块的数据都定义到一个store中,一般来说会一个模块对应一个store,最后通过一个根store进行整合

假设我们目前store中有两个模块user.js和counter.js,我们再手动设置一个index.js

1.我们在index.js中导入user.js和counter.js,

2.并统一导出useStore方法,返回user和counter中的内容

1
2
3
4
5
6
7
8
9
import useCounterStore from './counter.js'
import useUserStore from './user.js'

export default function useStore(){
return {
user:useUserStore(),
counter:useCounterStore()
}
}

3.那么如何在组件中具体使用呢?

首先从store/index.js导入useStore方法

由于使用useStore方法会返回一个对象,对象中有user和counter,

我们使用解构赋值可以从useStore方法得到具体的某个模块

注意:import useStore from ‘./store’ 虽然没有在后面加上/index.js,但是会默认选中文件夹下的index.js

1
2
3
4
5
6
7
8
9
10
<script setup>
import useStore from './store'
const { counter } = useStore()
</script>

<template>
<div>主页组件</div>
<div>计数:{{ counter.count }}</div>
<div>计数加倍: {{ counter.double }}</div>
</template>
vuex中实现模块化的方法

1.把各个模块导入index.js 2.把所有模块名放到mudules下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
import menu from './modules/menu'

Vue.use(Vuex)

const store = new Vuex.Store({
modules: {
app,
settings,
user,
menu
},
getters
})

export default store

pinia如何实现数据持久化?

我们可以通过通过 Pinia 插件pinia-plugin-persistedstate实现持久化存储

配置pinia持久化插件

1.下载安装pinia-plugin-persistedstate

2.main.js导入pinia-plugin-persistedstate创建对象并挂载

3.在具体的pinia模块中开启持久化

下载安装插件

1
2
3
yarn add pinia-plugin-persistedstate
or
npm i pinia-plugin-persistedstate

在main.js中导入并且注册挂载

1
2
3
4
5
6
7
8
9
10
11
12
13
// 配置pinia持久化插件
// 1.下载安装pinia-plugin-persistedstate
// 2.main.js导入pinia-plugin-persistedstate创建对象并挂载
// 3.在具体的pinia模块中开启持久化
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

createApp(App).use(pinia).mount('#app')

注意:当createApp(App)需要挂载多个时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
createApp(App).use(router).use(pinia).mount("#app")
复制代码
在具体的pinia模块中开启持久化
在user.js中设置 persist: true

import {defineStore} from 'pinia'

const useUserStore = defineStore('user',{
state(){
return {
userInfo:{
name:'tom',
age:4
}
}
},
actions:{
addAge(){
this.userInfo.age++
}
},
getters:{

},
//开启数据持久化
persist: true
})

export default useUserStore

实现效果,state数据存储在了LocalStorage中
总结


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!