mutation.js代码:
changeRoute(state, val) { let routeList = state.routeList; let isFind = false; let findeIdex = 0; //菜单栏和下拉的二级菜单 if (val[‘type‘] == ‘header‘ || val[‘type‘] == ‘secondHeader‘) { routeList.length = 0; //顶级菜单清除缓存 localStorage.removeItem("routeList"); } let routes = routeList; let localStorageList = localStorage.getItem(‘routeList‘); if (localStorageList) { //当前页刷新,使用缓存数据 routes = JSON.parse(localStorageList as any); } //遍历是否有存入当前路由位置 for (let i = 0; i < routes.length; i++) { isFind = routes[i][‘name‘] == val[‘name‘]; if (isFind) { findeIdex = i; break; } }; if (isFind) { //有的话,清除当前路由以后的数据 routes.splice(findeIdex + 1, routes.length - findeIdex - 1); //修改缓存 localStorage.setItem(‘routeList‘, JSON.stringify(routes)); } else { //存入全局变量 routes.push(val); //设置缓存 localStorage.setItem(‘routeList‘, JSON.stringify(routes)); } }
页面使用:
//获取面包屑缓存
let localStorageList1 = localStorage.getItem(‘routeList‘); //ts写法 as any this.routeList = JSON.parse(localStorageList1 as any) ? JSON.parse(localStorageList1 as any) : { name: ‘test‘, url: ‘/test‘ };
知识点:
1、localstorage
2、JSON.stringify()的作用是将 JavaScript 值转换为 JSON 字符串,JSON.parse()将JSON字符串转为一个对象
原文地址:https://www.cnblogs.com/qiufang/p/11544538.html
时间: 2024-10-09 18:02:37