去除vue项目中的#及其ie9兼容性

一、如何去除vue项目中访问地址的#

  vue2中在路由配置中添加mode(vue-cli创建的项目在src/router/index.js)

 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路由原理

 

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配置为绝对路径,如下:

 1 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,且后台对访问地址有严格校验,不建议使用此种模式。若是内容有错误或遗漏,欢迎大家批评指正~

 

posted @ 2017-12-07 10:41  深海鱼veritas  阅读(7312)  评论(0编辑  收藏  举报