一、VueRouter默認路由顯示不出東西
當我們在Vue項目中使用VueRouter時,會發現直接訪問首頁的時候並沒有任何東西顯示出來,這是因為默認情況下,VueRouter需要依賴於兩個配置文件:
- router/index.js 用於配置VueRouter路由
- App.vue 用於引入VueRouter路由配置
在這兩個文件都被正確配置以後,我們才能看到頁面上正常的內容顯示。
二、Vue默認路由
當我們創建一個新的Vue項目的時候,默認情況下,Vue會自動為我們創建一個路由文件並進行配置。這個路由配置文件主要包括:
- / 路徑對應的組件:src/views/Home.vue
- /about 路徑對應的組件:src/views/About.vue
三、VueRouter路由的作用
VueRouter的主要作用是在Vue項目中實現客戶端路由的跳轉以及管理。它能夠監聽瀏覽器URL地址的變化,並將變化反映到Vue組件中,從而實現局部刷新的效果。
四、VueRouter的路由模式
VueRouter有兩種路由模式:hash
和history
。默認情況下,VueRouter的路由模式是hash
模式,它將路由信息保存在URL地址的#
後面。
如果我們想要改變VueRouter的路由模式,可以在router/index.js
文件中進行如下配置:
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
})
export default router
以上配置表示將VueRouter的路由模式改為history
模式。
五、VueRouter動態添加路由
除了在router/index.js
中靜態配置路由信息以外,我們還可以在Vue組件中動態添加路由。
在Vue組件中動態添加路由的代碼如下:
import { useRouter } from 'vue-router'
const router = useRouter()
function addRoute() {
router.addRoute({
path: '/dynamic-route',
component: DynamicRoute
})
}
以上代碼表示在/dynamic-route
路徑下動態添加一個組件DynamicRoute
作為路由。
六、路由器默認mercury
除了VueRouter默認的hash
模式和history
模式以外,還有一個名為mercury
的路由模式。
我們可以在router/index.js
中進行如下配置,即可將VueRouter的路由模式改為mercury
模式:
import { createRouter, createMemoryHistory } from 'vue-router'
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
})
export default router
七、VueRouter路由跳轉
VueRouter提供了兩種方式進行路由跳轉:
router-link
標籤在template
中,用於生成可點擊的鏈接router.push
方法在JS代碼中,用於編程式地進行路由跳轉
路由跳轉的代碼示例:
<!-- 路由鏈接 -->
<router-link to="/">首頁</router-link>
<!-- JS代碼中的路由跳轉 -->
function navigateToAboutPage() {
router.push('/about')
}
八、VueRouter嵌套路由
VueRouter支持嵌套路由,也就是說一個路由下面還可以有它的子路由。
在router/index.js
中進行嵌套路由配置示例:
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{
path: '/about',
component: About,
children: [
{ path: '', component: AboutHome },
{ path: 'contact', component: AboutContact },
{ path: 'team', component: AboutTeam }
]
}
]
})
export default router
以上代碼表示在/about
路由下面嵌套了三個子路由,分別是/about
、/about/contact
和/about/team
。
九、VueRouter清空路由
我們可以使用router.replace
方法來清空路由,代碼示例如下:
const clearRoute = () => {
router.replace('/')
}
以上代碼表示將路由清空,回到/
路徑。
十、VueRouter路由模式區別選取
在選擇VueRouter的路由模式時,需要根據具體的需求來進行選擇。
hash
模式適合單頁應用,因為在單頁應用中,所有頁面切換都是在同一個頁面內完成的,使用hash
模式可以避免在伺服器端進行URL地址的配置。
history
模式適合支持伺服器端渲染的多頁應用,因為history
模式需要在伺服器端進行URL地址的配置。
merucry
模式主要是為了提高性能而創建的,它採用HTML5 PushState來實現路由跳轉,相比於hash
模式和history
模式,可以提供更好的性能和更好的用戶體驗。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/241722.html