首页 > 编程 > JavaScript > 正文

Vue实现远程获取路由与页面刷新导致404错误的解决

2019-11-19 12:11:25
字体:
来源:转载
供稿:网友

一、背景

先简单介绍一下现在项目情况:前后端分离,后端服务是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;}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表