Vue實現遠程獲取路由與頁面刷新導致404錯誤的解決


一、背景

  先簡單介紹一下現在項目情況:前后端分離,后端服務是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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM