拦截器:
基本路径:axios.defaults.baseURL = 'http://127.0.0.1:3000/'
1. 请求拦截器
async await
let res = await axios.get('/init', { mask: true });mask代表是否开启遮罩,请求结束后自动关闭
2. 路由拦截器及动态添加路由
router.beforeEach(async (to, from, next) => { let res = await axios.get('/get_router'); // 1、数据加工 let routerData = res.data.router.forEach(item => { routes.push({ path: name: meta: { title: item.title }, component: () => imnport(
../views/${item.component}) }) }) // 2、动态添加路由数据 router.addRoutes(routerData); })
缺点: 服务器压力增大,使用缓存(vuex)解决。
import store from '@/store'; if (store && store.state.nav.length === 1) { // 请求路由数据,数据缓存 store.dispatch('SETNAV', res.data.result); router.addRoutes(routerData); next({path: to.path}); } else { next(to.psth); }
页面刷新,请求两次,将导航组件中获取路由方式改为从缓存中读取 $store.state.nav 或者 computed: mapGetters(['getNav']), mapGetters: Vuex辅助函数,