1. 程式人生 > 其它 >vue路由模式

vue路由模式

路由模式

  vue-router 預設 hash 模式 —— 使用 URL 的 hash 來模擬一個完整的 URL,於是當 URL 改變時,頁面不會重新載入

http://localhost:8080/#/Hello

  如果不想要很醜的 hash,可以用路由的 history 模式,這種模式充分利用 history.pushState API 來完成 URL 跳轉而無須重新載入頁面

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

  當使用 history 模式時,URL 就像正常的 url

http://localhost:8080/Hello

  不過這種模式需要後臺配置支援。如果後臺沒有正確的配置,當用戶在瀏覽器直接訪問 http://oursite.com/user/id 就會返回 404

【伺服器配置】

  如果要使用history模式,則需要進行伺服器配置

  所以,要在服務端增加一個覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態資源,則應該返回同一個 index.html 頁面,這個頁面就是app 依賴的頁面

  下面是一些配置的例子

apache

  以wamp為例,需要對httpd.conf配置檔案進行修改

  首先,去掉rewrite_module前面的#號註釋

LoadModule rewrite_module modules/mod_rewrite.so

  然後,將文件所有的AllowOverride設定為all

AllowOverride all

  

【注意事項】

  這麼做以後,伺服器就不再返回404錯誤頁面,因為對於所有路徑都會返回 index.html 檔案。為了避免這種情況,應該在Vue應用裡面覆蓋所有的路由情況,然後再給出一個404頁面

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '*', component: NotFoundComponent }
  ]
})

  或者,如果是用 Node.js 作後臺,可以使用服務端的路由來匹配 URL,當沒有匹配到路由的時候返回 404,從而實現 fallback

const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const NotFound = {template:'<div>not found</div>'}

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar },
  { path: '*', component: NotFound},
]

Go to Foo Go to Bar 不存在的連結

not found