vuex+localStorage实现vue-element-admin模板刷新页面记忆选项卡

实现目标是刷新页面后,处于中间的选项卡会跟关闭页面前一样 

如你所见,我用的vue-element-admin的基础版vue-admin-template-master

示例:

vuex+localStorage实现vue-element-admin模板刷新页面记忆选项卡_第1张图片 

vuex+localStorage实现vue-element-admin模板刷新页面记忆选项卡_第2张图片

vuex+localStorage实现vue-element-admin模板刷新页面记忆选项卡_第3张图片 

vue-element-admin模板是没有这个刷新页面后还有选项卡记忆的功能的

实现方式:vuex保存页面状态,localStorage保存页面状态到浏览器里面

在src/utils下新建sessionStorageUtil.js和tagViewCache.js

/**
 * 封装存储localStorage,可以设定过期时间
 * @param {Object} key 存放的key值
 * @param {Object} val 存放的value值
 * @param {Object} time 设定的过期时间,单位为秒
 */
export function loca_setItem(key, val, time) {
	if (time) {
		var value = {
			val: val,
			c_time: new Date().getTime(),
			time: time * 1000
		}
		localStorage.setItem(key, JSON.stringify(value));
	} else {
		localStorage.setItem(key, JSON.stringify(val));
	}
}
/**
 * 封装localStorage的getItem函数
 * @param {Object} key 需要获取的key值
 */
export function loca_getItem(key) {
	if (localStorage.getItem(key)) {
		var val = JSON.parse(localStorage.getItem(key));
		if (val.c_time) {
			var n_time = new Date().getTime();
			if (n_time <= (val.c_time + val.time)) {
				return val.val;
			} else {
				localStorage.removeItem(key);
				return "";
			}
		} else {
			return val;
		}
	} else {
		return "";
	}
}

/**
 * 封装localStorage的removeItem函数
 * @param {Object} key 需要删除的key值
 */
export function loca_removeItem(key) {
	localStorage.removeItem(key);
}

/**
 * 循环删除key数组
 * @param {Object} keys 需要删除的key数组
 */
export function loca_removeItems(keys) {
	for (var k in keys) {
		myapp.loca_removeItem(keys[k]);
	}
}
import {
  loca_setItem,
  loca_getItem,
  loca_removeItem
} from '@/utils/sessionStorageUtil.js'

const tagViewCacheName = 'tagViewCacheName'

export function getTagViewCache() {
  return loca_getItem(tagViewCacheName)
}

function e(view) {
  return {
    fullPath: view.fullPath,
    hash: view.hash,
    meta: {
      title: view['meta'].title
    },
    path: view.path,
    query: view.query
  }
}
export function setTagViewCache(view) {
  let a = getTagViewCache()
  let v = e(view)
  if (a) {
    a.push(v)
  } else {
    a = []
    a.push(v);
  }
  return loca_setItem(tagViewCacheName, a)
}

export function deleteTagViewCache(view) {
  let v = e(view)
  let a = getTagViewCache();
  for (var k in a) {
    if (v.path == a[k].path) {
      a.splice(k, 1);
    }
  }
  return loca_setItem(tagViewCacheName, a)
}

在src/store下面编辑tagsView.js

在头部添加

import { getTagViewCache, setTagViewCache, deleteTagViewCache } from '@/utils/tagViewCache'

在addVisitedView和delVisitedView方法处添加

addVisitedView({ commit }, view) {
    setTagViewCache(view)
    let a = getTagViewCache()
    for(var k in a){
    commit('ADD_VISITED_VIEW', a[k])
    }
  },
delVisitedView({ commit, state }, view) {
    return new Promise(resolve => {
      deleteTagViewCache(view)
      commit('DEL_VISITED_VIEW', view)
      resolve([...state.visitedViews])
    })
  },

 然后就可以了

你可能感兴趣的:(vue,vue.js,前端,javascript)