Vue实现远程获取路由与页面刷新导致404错误的解决
一、背景
先简单介绍一下现在项目情况:前后端分离,后端服务是Java写的,前端是Vue+ElementUI。
最近的一个需求是:通过后端Api去获取前端路由表,原因是每个登录角色对应的前端路由表可能是不一样的(权限问题)
二、遇到的问题
因为前端Vue+ElementUI项目是单页应用——即只有一个index.html页面,如果路由从远程获取的话,每次F5或点击刷新按钮刷新页面的时候,就会找不到对应的路径而报404错误
三、解决方案
1、通过api远程获取路由,然后在前端生成对应路由
/*
将服务器获得的[路由json字符串]转换成可访问的[前端路由组件]
@remoteRouterMap服务器获得的[路由json字符串]
*/
functiontransformJsonToRouter(remoteRouterMap){
constaccessedRouters=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)
}
returntrue
})
returnaccessedRouters
}
2、将路由模式改成history模式(vue默认是hash模式)
exportdefaultnewRouter({
mode:'history',//后端支持可开
scrollBehavior:()=>({y:0}),
routes:constantRouterMap,
linkActiveClass:'is-active'
})
3、在nginx中设置将404错误指向index文件
location/{
try_files$uri$uri//index.html;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。