一、背景
先簡單介紹一下現在項目情況:前后端分離,后端服務是Java寫的,前端是Vue+ElementUI。
最近的一個需求是:通過后端Api去獲取前端路由表,原因是每個登錄角色對應的前端路由表可能是不一樣的(權限問題)
二、遇到的問題
因為前端Vue+ElementUI項目是單頁應用――即只有一個index.html頁面,如果路由從遠程獲取的話,每次F5或點擊刷新按鈕刷新頁面的時候,就會找不到對應的路徑而報404錯誤
三、解決方案
1、通過api遠程獲取路由,然后在前端生成對應路由
/* 將 服務器獲得的[路由json字符串]轉換成可訪問的[前端路由組件] @remoteRouterMap 服務器獲得的[路由json字符串]*/function transformJsonToRouter(remoteRouterMap) { const accessedRouters = remoteRouterMap.filter(route => { if (!route.component) { route.component = Layout }else { route.component = route.component.replace("@/views/","") route.component = _import(route.component) } if (route.children && route.children.length) { route.children = transformJsonToRouter(route.children) } return true }) return accessedRouters}
2、將路由模式改成history模式(vue默認是hash模式)
export default new Router({ mode: 'history', //后端支持可開 scrollBehavior: () => ({ y: 0 }), routes: constantRouterMap, linkActiveClass: 'is-active'})
3、在nginx中設置將404錯誤指向index文件
location / { try_files $uri $uri/ /index.html;}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答