Vue Router 4.x 常用 API 介绍

169 阅读2分钟

Vue Router 4.x 是专为 Vue 3 设计的路由管理器,提供了强大的路由功能来构建单页应用(SPA)。以下是 Vue Router 4.x 中一些常用 API 的介绍和用法示例。

安装 Vue Router

首先,确保已经安装了 Vue Router 4.x。如果尚未安装,可以通过 npm 安装:

npm install vue-router@4

初始化和配置路由

创建路由实例

import { createRouter, createWebHistory } from 'vue-router';

const routes = [
    { path: '/', component: () => import('./components/Home.vue') },
    { path: '/about', component: () => import('./components/About.vue') },
    // 更多路由...
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

export default router;

在 Vue 应用中使用路由

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

const app = createApp(App);

app.use(router);

app.mount('#app');

路由导航

编程式导航

  • router.push:导航到不同的 URL。
router.push('/about');
  • router.replace:导航到不同的 URL,但不会在历史中留下记录。
router.replace('/about');
  • router.go:前进或后退特定的历史记录数。
router.go(-1); // 后退

声明式导航

使用 <router-link> 组件进行导航。

<template>
  <router-link to="/">Home</router-link>
  <router-link to="/about">About</router-link>
</template>

动态路由匹配

可以使用带参数的路由来捕获动态片段。

const routes = [
    { path: '/user/:id', component: () => import('./components/User.vue') }
];

嵌套路由

通过在路由配置中使用 children 属性来定义嵌套路由。

const routes = [
    {
        path: '/user/:id',
        component: () => import('./components/User.vue'),
        children: [
            {
                path: 'profile',
                component: () => import('./components/UserProfile.vue')
            }
            // 更多子路由...
        ]
    }
];

路由守卫

全局守卫

  • beforeEach:在路由进入前执行。
router.beforeEach((to, from, next) => {
    // 权限检查或其他逻辑
    next();
});

路由独享的守卫

在路由配置中定义 beforeEnter 守卫。

const routes = [
    { 
        path: '/protected',
        component: () => import('./components/Protected.vue'),
        beforeEnter: (to, from, next) => {
            // 权限检查或其他逻辑
            next();
        }
    }
];

组件内的守卫

在 Vue 组件内部使用 beforeRouteEnterbeforeRouteUpdatebeforeRouteLeave

<script>
export default {
    beforeRouteEnter(to, from, next) {
        // 在渲染该组件的对应路由被 confirm 前调用
        next();
    },
    beforeRouteUpdate(to, from, next) {
        // 在当前路由改变,但是该组件被复用时调用
        next();
    },
    beforeRouteLeave(to, from, next) {
        // 导航离开该组件的对应路由时调用
        next();
    }
}
</script>

结语

Vue Router 4.x 提供了强大而灵活的路由管理功能,适用于 Vue 3 应用。通过这些常用的 API 和配置,你可以在 Vue 项目中实现复杂的路由需求,包括动态路由、嵌套路由、导航守卫等。