vue2中在路由配置中添加mode(vue-cli建立的项目在src/router/index.js)javascript
1 export default new Router({ 2 mode: 'history', 3 routes: [ 4 { 5 path: '/', 6 name: 'menu', 7 component: menu, 8 children: [ 9 { 10 path: 'organization', 11 component: organization, 12 children: [ 13 { 14 path: '', 15 redirect: 'organizationSub' 16 }, 17 { 18 path: 'organizationSub', 19 component: organizationSub 20 } 21 ] 22 }, 23 { 24 path: 'user', 25 component: user 26 }, 27 { 28 path: 'role', 29 component: role 30 } 31 ] 32 } 33 ] 34 })
vue开发的单页面应用,html只有一个,切换时url的变化经过url的hash模式模拟完整的url。html
利用history.pushState API完成url的跳转vue
HTML5 History 模式官网介绍:https://router.vuejs.org/zh-cn/essentials/history-mode.htmljava
3、注意事项web
不过这种模式要玩好,还须要后台配置支持。由于咱们的应用是个单页客户端应用,若是后台没有正确的配置,当用户在浏览器直接访问
http://oursite.com/user/id
就会返回 404,这就很差看了。vue-router因此呢,你要在服务端增长一个覆盖全部状况的候选资源:若是 URL 匹配不到任何静态资源,则应该返回同一个
index.html
页面,这个页面就是你 app 依赖的页面。vue-cli——vue-router官网浏览器
vue-router官网中有介绍,也有后台配置样例:https://router.vuejs.org/zh-cn/essentials/history-mode.htmltomcat
确保在config->index.js中,build下assetsPublicPath配置为绝对路径,以下:app
1 build: {assetsPublicPath: '/' }
在tomcat->conf->web.xml中添加以下配置:
<error-page> <error-code>404</error-code> <location>/index.html</location> </error-page>
在项目中亲测。
4、兼容性
通过测试,mode: 'history'在ie9下不生效,若vue项目须要兼容ie9,且后台对访问地址有严格校验,不建议使用此种模式。如果内容有错误或遗漏,欢迎你们批评指正~