簡單上手 Vue Router
Vue Router 也隨著 Vue3 的更新來到了 4 版本,來看一下怎么使用吧!(這里使用的是 composition API 和 TypeScript 模式)
安裝 vue-router4
npm install vue-router@4
在 /src 下新建 router/index.ts
import {
createRouter,
createWebHashHistory,
createWebHistory,
RouteRecordRaw
} from 'vue-router'
const routes:Array<RouteRecordRaw> = [...]
const router = createRouter({
history: createWebHashHistory(),
/*
* 如果配置的是 createWebHashHistory 則瀏覽器地址欄所
* 顯示的路徑中會(huì)帶有 "#" 號(hào)
* 如果使用 createWebHistory 則不會(huì)出現(xiàn)
*/
routes
})
export default router
routes 里面配置的是路由數(shù)組
以下是我的路由數(shù)組
const routes:Array<RouteRecordRaw> = [
{
path: '/',
component: () => import('@/components/IndexPage.vue'),
},
{
path: '/login',
component: () => import('@/components/LoginPage.vue')
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('@/components/404.vue')
}
]
路徑里的
@符代表src路徑,可以參考以前的文章,最后一個(gè)路由的path內(nèi)的內(nèi)容表示未匹配的路徑
配置子路由
{
path: '/',
component: () => import('@/components/IndexPage.vue'),
children: [
{
path: '/',
component: () => import('@/components/page/OneSubPage.vue')
},
{
path: '/two-sub-page',
component: () => import('@/components/page/TwoSubPage.vue')
}
]
},
這里給 IndexPage 下的頁面放置了兩個(gè)子頁面,分別為 OneSubPage 和 TwoSubPage,配置子路由的方式基本和一級(jí)路由一樣。
在 main.ts 中注冊路由
main.ts 是我們整個(gè)項(xiàng)目的入口文件
import { createApp } from 'vue'
import App from './App.vue'
import router from '@/router'
createApp(App).use(router).mount('#app')
在 App.vue 中配置 router-view
<template>
<router-view></router-view>
</template>
這里只寫了幾個(gè)簡單的頁面來展示路由功能,具體代碼就不放了 ??
測試路由
嘗試下啟動(dòng)項(xiàng)目,并在瀏覽器打開:

默認(rèn)的路徑為 /,所進(jìn)入的路由頁面是 IndexPage -> OneSubPage
如果想進(jìn)入當(dāng)前一級(jí)路由的第二個(gè)子路由:

如果想進(jìn)入另一個(gè)一級(jí)路由:

路由跳轉(zhuǎn)
這里先簡單展示一下一個(gè)路由跳轉(zhuǎn)按鈕的代碼吧 ??
<template>
<button @click="login">登錄</button>
</template>
<script lang="ts" setup>
import {useRouter} from 'vue-router';
// 定義路由器,負(fù)責(zé)路由跳轉(zhuǎn)
const router = useRouter();
// 登錄按鈕:路由跳轉(zhuǎn)
function login() {
router.push('/');
}
</script>

浙公網(wǎng)安備 33010602011771號(hào)