Vue3 vue-router 路由管理

在 Vue 3 中,使用 vue-router 进行路由管理是构建 SPA(单页应用)时的常见做法。这里我将介绍以下几个核心知识点:路由的安装和引用、动态路由、参数传递、嵌套路由、命名路由、命名视图和路由守卫。

1. 路由的安装和引用

安装 vue-router

在 Vue 3 项目中使用 vue-router,首先需要安装它:

npm install vue-router@4
引用并配置路由

安装完成后,你需要在项目中引用 vue-router,并创建一个路由实例,将其绑定到 Vue 应用中。

src/router/index.js(路由配置)

import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
];

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

export default router;

src/main.js(在 Vue 实例中引用路由)

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

const app = createApp(App);
app.use(router);  // 使用路由
app.mount('#app');

2. 动态路由

动态路由用于根据 URL 的参数显示不同的内容。你可以在路由路径中使用 :param 来表示动态参数。

示例:动态路由

src/router/index.js(配置动态路由)

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

src/views/UserProfile.vue(接收路由参数)

<template>
  <div>
    <h2>User Profile</h2>
    <p>User ID: {{ $route.params.id }}</p>
  </div>
</template>
路由传参

使用 router-link 来传递动态参数:

<router-link :to="{ name: 'UserProfile', params: { id: 123 } }">
  Go to User 123's profile
</router-link>

3. 参数传递

路由参数传递有两种方式:通过 路由参数params)和 查询参数query)。

路由参数
const routes = [
  {
    path: '/user/:id',
    component: UserProfile
  }
];

访问时,通过 this.$route.params.id 获取参数。

查询参数
<router-link :to="{ name: 'UserProfile', query: { id: 123 } }">
  Go to User 123's profile (Query)
</router-link>

访问时,通过 this.$route.query.id 获取查询参数。

4. 嵌套路由

嵌套路由是路由之间的层级关系,常用于展示父子组件之间的结构。

示例:嵌套路由

src/router/index.js

const routes = [
  {
    path: '/',
    component: Home,
    children: [
      {
        path: 'about',
        component: About
      }
    ]
  }
];

src/views/Home.vue(父组件)

<template>
  <div>
    <h2>Home Page</h2>
    <router-view></router-view>  <!-- 嵌套子路由 -->
  </div>
</template>

src/views/About.vue(子组件)

<template>
  <div>
    <h3>About Page</h3>
  </div>
</template>

5. 命名路由

命名路由使得在进行路由跳转时更加直观和灵活。你可以给每个路由配置一个 name,并通过路由的 name 来跳转。

示例:命名路由

src/router/index.js

const routes = [
  {
    path: '/about',
    name: 'about',
    component: About
  }
];

使用 router-link 跳转时,通过 name 进行导航:

<router-link :to="{ name: 'about' }">Go to About</router-link>

6. 命名视图

命名视图允许在同一个页面中渲染多个视图区域。

示例:命名视图

src/router/index.js

const routes = [
  {
    path: '/',
    components: {
      default: Home,    // 默认视图
      sidebar: Sidebar  // 命名视图
    }
  }
];

src/views/Home.vue

<template>
  <div>
    <h2>Main Content</h2>
    <router-view></router-view>  <!-- 默认视图 -->
    <router-view name="sidebar"></router-view>  <!-- 命名视图 -->
  </div>
</template>

src/views/Sidebar.vue(侧边栏视图)

<template>
  <div>
    <h3>Sidebar</h3>
  </div>
</template>

7. 路由守卫

路由守卫用于控制路由的进入、离开等操作。Vue Router 提供了几种路由守卫,如全局守卫、路由独享守卫和组件内守卫。

示例:全局前置守卫

全局前置守卫用于在路由跳转之前进行一些检查,例如,判断是否登录。

router.beforeEach((to, from, next) => {
  // 如果目标路由需要登录,且用户没有登录,跳转到登录页面
  if (to.meta.requiresAuth && !isLoggedIn()) {
    next({ name: 'Login' });
  } else {
    next();  // 继续路由跳转
  }
});
路由独享守卫

每个路由可以有独享守卫,可以在路由定义中进行设置。

const routes = [
  {
    path: '/profile',
    component: Profile,
    beforeEnter: (to, from, next) => {
      if (isAuthenticated()) {
        next();  // 允许访问
      } else {
        next({ name: 'Login' });  // 重定向到登录页面
      }
    }
  }
];
组件内守卫

组件内守卫可以在组件中定义,如 beforeRouteEnterbeforeRouteLeave

export default {
  beforeRouteEnter(to, from, next) {
    // 在路由进入之前进行操作
    console.log('Before entering route');
    next();
  },
  beforeRouteLeave(to, from, next) {
    // 在路由离开之前进行操作
    console.log('Before leaving route');
    next();
  }
};

总结

  1. 安装和引用: 安装 vue-router,配置路由实例,并在 main.js 中引用。
  2. 动态路由: 使用 :param 定义动态路由,在组件中通过 this.$route.params 访问。
  3. 参数传递: 使用路由参数(params)和查询参数(query)传递数据。
  4. 嵌套路由: 配置路由的层级关系,子路由通过 router-view 显示。
  5. 命名路由: 给路由命名,并通过 name 进行跳转。
  6. 命名视图: 允许在同一页面渲染多个视图区域。
  7. 路由守卫: 使用路由守卫进行访问控制和处理路由生命周期事件。

这些是 Vue Router 中的基本用法,你可以根据实际需求进行灵活运用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值