一、如何去除vue项目中访问地址的#
vue2中在路由配置中添加mode(vue-cli创建的项目在src/router/index.js)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'menu',
component: menu,
children: [
{
path: 'organization',
component: organization,
children: [
{
path: '',
redirect: 'organizationSub'
},
{
path: 'organizationSub',
component: organizationSub
}
]
},
{
path: 'user',
component: user
},
{
path: 'role',
component: role
}
]
}
]
})
二、vue路由原理
2.1 hash模式:vue-router默认的路由模式。
vue开发的单页面应用,html只有一个,切换时url的变化通过url的hash模式模拟完整的url。
2.2 history模式:vue2中配置 mode: 'history'。
利用history.pushState API完成url的跳转
HTML5 History 模式官网介绍:https://router.vuejs.org/zh-cn/essentials/history-mode.html
三、注意事项
3.1 后台配置
不过这种模式要玩好,还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问
http://oursite.com/user/id
就会返回 404,这就不好看了。所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个
index.html
页面,这个页面就是你 app 依赖的页面。——vue-router官网
vue-router官网中有介绍,也有后台配置样例:https://router.vuejs.org/zh-cn/essentials/history-mode.html
3.2 打包配置
确保在config->index.js中,build下assetsPublicPath配置为绝对路径,如下:
build: {assetsPublicPath: '/' }
3.3 Tomcat配置
在tomcat->conf->web.xml中添加如下配置:
<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>
在项目中亲测。
四、兼容性
经过测试,mode: 'history'在ie9下不生效,若vue项目需要兼容ie9,且后台对访问地址有严格校验,不建议使用此种模式。若是内容有错误或遗漏,欢迎大家批评指正~