2023-01-16
Vue3 使用 Vite 整合 axios 攔截器與 axios proxy
Vue
2022.04.20
最近在帶新人同事規劃部落格的網址結構,因為想讓他嘗試實作自己的構思,所以就讓他自由發揮啦!
這是同事規劃出來的網址結構:
/topic
/topic/:pageIndex
/topic/category/:categoryName
/topic/category/:categoryName/:pageIndex
/topic/article?id={id}
一開始只做首頁與分頁時,路由規劃如下,一切都如此單純美好:
{ path: '/topic/:pageIndex', component: 'topicView' }
接著我請他加入分類與單篇文章的路由,同事一開始是這樣寫的:
{ path: '/topic/:pageIndex', component: 'topicView', children: [ { path: 'category/:name/:pageIndex', component: 'categoryView' }, { path: 'article', component: 'articleView' } ] }
然後問題就來了!
因為結構的問題,Vue 會把巢狀路由的 category
當成 :pageIndex
的參數,傳到 /topic/
裡面,因此不管怎麼調整,都沒辦法顯示正確的網址。
我的處理方法,是把 :pageIndex
也變成巢狀路由:
{ path: '/topic', component: 'topicView', children: [ { path: ':pageIndex', component: 'indexView' }, { path: 'category/:name/:pageIndex', component: 'categoryView' }, { path: 'article', component: 'articleView' } ] }
不過這樣改完還是沒效果,那是因為 :pageIndex
會優先被渲染,但我們希望可以先考慮 category
以及 article
這兩個路徑,所以只要將 :pageIndex
放在後面,讓他最後被渲染即可:
{ path: '/topic', component: 'topicView', children: [ { path: 'category/:name/:pageIndex', component: 'categoryView' }, { path: 'article', component: 'articleView' }, { path: ':pageIndex', component: 'indexView' }, ] }
修改過後,當今天路徑為 /topic/category/cateA/1
時,就能優先渲染,不會被 :pageIndex
截胡啦。