vuex刷新之后数据丢失,各种解决方案

版权声明:仅供参考学习。 https://blog.csdn.net/weixin_43206949/article/details/88841472

为什么刷新之后vuex的状态就没了?
原因是刷新之后js初始化,vuex重新初始化了;
常见的解决方案有
1,mounted里面调接口重新给state赋值,太麻烦,pass
2,watch里面监听state,再赋值,也很low
vuex理解不透彻的可以先看看
完美方案是利用sessionStorage/localStorage,做一个暂时的储存
store的模块化结构
在这里插入图片描述
主要是针对mutations 和 getters 做一个简单的赋值和取值封装
mutations.js改变state的同时在本地做一个备份

const setStorage = (key, value) => {
  if (typeof (value) === 'object') {
    value = JSON.stringify(value)
  }
  sessionStorage.setItem(key, value)
}
/*
* 避免刷新之后vuex被重置,在sessionStorage做一个备份
 */
const mutations = {
  set_userInfo (state, payload) {
    state.userInfo = payload
    setStorage('userInfo', payload)
  },
  set_token (state, payload) {
    state.token = payload
    setStorage('token', payload)
  },
  set_roles (state, payload) {
    state.roles = payload
    setStorage('roles', payload)
  },
  set_breadcrumb (state, payload) {
    state.breadcrumb = payload
    setStorage('breadcrumb', payload)/*  */
  }
}
export default mutations

getters.js 取值时默认从state里面取,没有就从本地拿

import createdRoutes from '@/utils/createdRoutes.js'
import { asyncRoutes } from '@/router/index.js'
let getStoryage = (item) => {
  let str = sessionStorage.getItem(item)
  return JSON.parse(str)
}
const getters = {
  get_userInfo: (state) => {
    return state.userInfo ? state.userInfo : getStoryage('userInfo')
  },
  get_token: (state) => {
    return state.token ? state.token : sessionStorage.getItem('token')
  },
 get_roles: (state) => {
    return state.roles.length ? state.roles : getStoryage('roles')
  },
  addRouters: (state, getters) => {
    let routes = createdRoutes(asyncRoutes, getters.get_roles)
    return routes
  },
  get_breadcrumb: (state, getters) => {
    return state.breadcrumb.length ? state.breadcrumb : getStoryage('getStoryage')
  }
}
export default getters;

在页面vue文件直接用mapGetters获取状态值
这样一来就算state被清空了,还可以在本地储存里面获取状态值

后记:

本来想写一个插件完成上面的事,结果发现一个已经写好的 vuex-persistedstate
用法:
https://www.cnblogs.com/lemoncool/p/9645587.html

展开阅读全文

没有更多推荐了,返回首页