preface
Vuex is required for routing persistence and record with NUXT framework.
Introduce methods
1. Install
npm install vuex-persistedstate --save
Copy the code
Nuxt.config. js configuration file
plugins: [
{ src: '~/plugins/vuex-persistedstate', ssr: false },
],
Copy the code
plugins/vue-persistedstate.js
import createPersistedState from 'vuex-persistedstate' export default (context) => { createPersistedState({ reducer(obj) State const {username, authority} = obj; return {username, authority } } })(context.store); }Copy the code
store/index.js
import createPersistedState from "vuex-persistedstate"
export const plugins = [createPersistedState()];
Copy the code
If you want to store to sessionStorage and specify a storage variable:
export const plugins = [createPersistedState({ storage: Window. The sessionStorage, reducer (val) {return {/ / stored in the state only assessmentData username: val. The username, authority: val.authority, } } })];Copy the code
2. Use
store/index.js
export const state = () => ({
username: '',
authority: '',
});
export const mutations = {
setUsername: (state, value) => state.username = value,
setAuthority: (state, value) => state.authority = value,
};
Copy the code
Where set is needed in the project:
this.$store.commit('setUsername', value);
Copy the code
Where you need to get in your project:
this.$store.state.username; / / get the usernameCopy the code
3. Hit the pit
Window is not defined
-
Check whether SSR is set to false in nuxt.config.js
-
Set mode to ‘spa’ in nuxt.config.js
Reference website:
Juejin. Cn/post / 684490…
Github.com/championswi…
Github.com/nuxt/nuxt.j…