1.在model文件夹下面新建一个storage.js
 

const storage = {
  set(key,value){
    sessionStorage.setItem(key,JSON.stringify(value));
  },
  get(key){
    return JSON.parse(sessionStorage.getItem(key));
  },
  getForIndex(index){
    return sessionStorage.key(index)
  },
  getKeys(){
    let items = this.getAll();
    let keys = [];
    for(let index = 0;index<items.length;index++){
      keys.push(items[index].key);
    }
  },
  getLength(){
    return sessionStorage.length;
  },
  getSupport(){
    return (typeof (Storage) !== "undefined")?true:false;
  },
  remove(key){
    sessionStorage.removeItem(key);
  },
  removeAll(){
    sessionStorage.clear();
  },
  getAll(){
    let len = sessionStorage.length;
    let arr = [];
    for(let i=0;i<len.length;i++){
      const getKey =  sessionStorage.key(i);
      const getVal = sessionStorage.getItem(getKey);
      arr[i] = {
        "key":getKey,
        "val":getVal,
      }
    }
    return arr;
  },
};

export default storage;

2.创建store

import Vue from "vue";
import Vuex from "vuex";
import storage from "@/model/storage";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    //  存储token
    token: '',
    userName: '',
    roleId:'',
    staticRoute:[]//这个是本地路由
  },

  actions: {
    setuserInfoFun(context, name){
      context.commit('setuserInfo', name);
    },
    set_tokenFun(context, token){
      context.commit('set_token', token)
    },
    del_tokenFun(context){
      context.commit('del_token')
    },
    set_roleIdFun(context,id){
      context.commit('set_roleId',id)
    },
    set_routerFun(context,route){
      context.commit('set_router',route)
    }
  },

//  计算属性
  mutations: {
    //  修改token,并将token存入localStorage
    set_token(state, token){
      state.token = token;
      storage.set('token', token);
    },
    del_token(state){
      state.token = "";
      storage.remove('token');
    },
    setuserInfo(state, userName){
      state.userName = userName;
    },
    set_roleId(state,id){
      state.roleId = id;
    },
    set_router(state,router){
      state.staticRoute = router;
      storage.set('route', router);
    }
  }
});

export default store;

 

 

 

 

 

 

Logo

前往低代码交流专区

更多推荐