vuex持久化存储vuex模块
时间: 2023-11-21 16:58:15 浏览: 92
为了实现Vuex模块的持久化存储,可以使用vuex-persistedstate插件。下面是实现Vuex模块持久化存储的步骤:
1. 安装vuex-persistedstate插件:
```shell
npm i vuex-persistedstate@3.2.1
```
2. 在Vuex store中引入vuex-persistedstate插件:
```javascript
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
// ...
plugins: [createPersistedState()]
})
```
3. 在Vuex store中定义需要持久化存储的模块:
```javascript
import user from './modules/user'
const store = new Vuex.Store({
modules: {
user
},
plugins: [createPersistedState()]
})
```
在上面的代码中,我们将user模块定义为需要持久化存储的模块。
4. 在需要持久化存储的模块中添加一个`namespaced`属性:
```javascript
const user = {
namespaced: true,
// ...
}
```
5. 在需要持久化存储的模块中添加一个`mutations`属性:
```javascript
const user = {
namespaced: true,
state: {
// ...
},
mutations: {
// ...
}
}
```
6. 在`mutations`中添加一个`RESTORE_MUTATION`:
```javascript
import { RESTORE_MUTATION } from 'vuex-persistedstate'
const user = {
namespaced: true,
state: {
// ...
},
mutations: {
[RESTORE_MUTATION] (state, payload) {
Object.assign(state, payload)
},
// ...
}
}
```
7. 在需要持久化存储的模块中添加一个`actions`属性:
```javascript
const user = {
namespaced: true,
state: {
// ...
},
mutations: {
// ...
},
actions: {
// ...
}
}
```
8. 在`actions`中添加一个`init`方法:
```javascript
const user = {
namespaced: true,
state: {
// ...
},
mutations: {
// ...
},
actions: {
init ({ commit }) {
commit(RESTORE_MUTATION, JSON.parse(localStorage.getItem('vuex')))
},
// ...
}
}
```
9. 在Vue应用的入口文件中调用`init`方法:
```javascript
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App),
created () {
this.$store.dispatch('user/init')
}
}).$mount('#app')
```
现在,我们已经成功地实现了Vuex模块的持久化存储。
阅读全文
相关推荐

















