一、如何去除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,且后臺對訪問地址有嚴格校驗,不建議使用此種模式。若是內容有錯誤或遺漏,歡迎大家批評指正~
?