Vuex – persistence

Purpose: To allow state data managed in VUEX to be stored locally simultaneously. Can avoid their own storage link.

  • During the development process, user information (name, avatar, token) needs to be stored in VUEX and stored locally.
  • For example, shopping carts are supported if they need to be logged in, and pages need to be stored locally if they need to be managed in VUEX.
  • We need the category module to store the category information, but the category information does not need to be persisted.

1) Firstly, we need to install a vuex plug-in, Vuex-PersistedState, to support vuex state persistence.

npm i vuex-persistedstate
Copy the code

2) Then: Create modules under SRC /store, user.js and cart.js under modules

src/store/modules/user.js

// export default {namespaced: true, state () {return {id: ", avatar: ", nickname:" '', account: '', mobile: '', token: '' } } }, mutations: SetUser (state, payload) {state.profile = payload}}Copy the code

src/store/modules/cart.js

Export default {namespaced: true, state: () => {return {list: []}}}Copy the code

3) Continue: import the User Cart module in SRC /store/index.js.

import { createStore } from 'vuex'

import user from './modules/user'
import cart from './modules/cart'

export default createStore({
  modules: {
    user,
    cart
  }
})

Copy the code

4) Finally: Use vuex-PersistedState for persistence

import { createStore } from 'vuex'
+import createPersistedstate from 'vuex-persistedstate'

import user from './modules/user'
import cart from './modules/cart'

export default createStore({
  modules: {
    user,
    cart
  },
+  plugins: [
+    createPersistedstate({
+      key: 'erabbit-client-pc-store',
+      paths: ['user', 'cart']
+    })
+  ]
})
Copy the code

Note:

===> By default, it is stored in localStorage

===> Key is the name of the key that stores data

===> Paths stores the data in the state. For specific data in the module, add the module name, such as user.token

===> The change of data stored locally can be seen only after state is triggered.

Conclusion:

  1. Persisting vuEX data based on third-party packages
  2. Persistence is triggered by a change in state