亲宝软件园·资讯

展开

Vue Strorage本地化存储

是阿岚呐 人气:0

Storage本地化存储

存储优点:

localStorage

sessionStorage

Strorage本地存储实例

在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;

创建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;

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论