前言
项目需求,需要vuex进行路由持久化保存,结合nuxt框架进行记录。
引入方法
1. 安装
npm install vuex-persistedstate --save
nuxt.config.js配置文件
plugins: [
{ src: '~/plugins/vuex-persistedstate', ssr: false },
],
plugins/vue-persistedstate.js
import createPersistedState from 'vuex-persistedstate'
export default (context) => {
createPersistedState({
reducer(obj) {
// 其中 username authority 为需要自动存储的 state
const { username, authority } = obj;
return {username, authority }
}
})(context.store);
}
store/index.js
import createPersistedState from "vuex-persistedstate"
export const plugins = [createPersistedState()];
如果想要存储到sessionStorage以及指定存储变量:
export const plugins = [createPersistedState({
storage: window.sessionStorage,
reducer(val) {
return {
// 只储存state中的assessmentData
username: val.username,
authority: val.authority,
}
}
})];
2. 使用
store/index.js
export const state = () => ({
username: '',
authority: '',
});
export const mutations = {
setUsername: (state, value) => state.username = value,
setAuthority: (state, value) => state.authority = value,
};
项目中需要set的地方:
this.$store.commit('setUsername', value);
项目中需要get的地方:
this.$store.state.username;//获取username
3. 踩坑
引入后可能出现window is not defined 问题:
-
检查nuxt.config.js中是否将ssr置为false
-
将nuxt.config.js中mode设置为'spa'