vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue Strorage本地化存储

Vue中的Strorage本地化存储详解

作者:是阿岚呐

这篇文章主要介绍了Vue中的Strorage本地化存储详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

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;

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

您可能感兴趣的文章:
阅读全文