一、如何去除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
三、注意事項
不過這種模式要玩好,還需要后臺配置支持。因為我們的應用是個單頁客戶端應用,如果后臺沒有正確的配置,當用戶在瀏覽器直接訪問 http://oursite.com/user/id 就會返回 404,這就不好看了。
所以呢,你要在服務端增加一個覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態資源,則應該返回同一個 index.html 頁面,這個頁面就是你 app 依賴的頁面。
vue-router官網中有介紹,也有后臺配置樣例:https://router.vuejs.org/zh-cn/essentials/history-mode.html
四、兼容性
經過測試,mode: 'history'在ie9下不生效,若vue項目需要兼容ie9,且后臺對訪問地址有嚴格校驗,不建議使用此種模式。若是內容有錯誤或遺漏,歡迎大家批評指正~
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com