In the project, we used persistence of data in many places, such as when storing tokens, or in the e-commerce platform, we need to keep the items added to the shopping cart before. So let’s see how this is implemented in Vue3
vuex-persistedstate
npm i vuex-persistedstate
Copy the code
2) Then: create a new modules file under SRC /store, and create 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 Cate module in SRC /store/index.js.
import { createStore } from 'vuex'
import user from './modules/user'
import cart from './modules/cart'
import cate from './modules/cate'
export default createStore({
modules: {
user,
cart,
cate
}
})
Copy the code
4) Finally: Use vuex-PersistedState for persistence
Import {createStore} from 'vuex' import createPersistedstate from 'vuex-PersistedState' import user from 'vuex-PersistedState' './modules/user' import cart from './modules/cart' import cate from './modules/cate' export default createStore({ Modules: {user, cart, cate}, plugins: [createPersistedstate({// '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:
- Persisting vuEX data based on third-party packages
- Persistence is triggered by a change in state