Vue Router 核心知识点

以下是 Vue Router 的核心知识点及示例说明,涵盖路由配置、导航守卫、动态路由、嵌套路由等核心功能:


一、路由配置

1. 基本路由定义

通过 routes 数组定义路径与组件的映射关系。

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

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

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

export default router;
2. 路由模式

支持 hashhistory 模式:

// Hash 模式(URL 带 #)
// createWebHashHistory()

// History 模式(需服务器配置)
createWebHistory();

二、导航守卫

1. 全局前置守卫(beforeEach

用于权限验证或全局拦截:

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token');
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login'); // 跳转到登录页
  } else {
    next(); // 放行
  }
});
2. 路由独享守卫(beforeEnter

在路由配置中定义:

const routes = [
  {
    path: '/admin',
    component: Admin,
    beforeEnter: (to, from, next) => {
      // 验证管理员权限
      next();
    }
  }
];
3. 组件内守卫

在组件中使用 onBeforeRouteUpdatebeforeRouteLeave

// Vue 3 组合式 API
import { onBeforeRouteLeave } from 'vue-router';

export default {
  setup() {
    onBeforeRouteLeave((to, from, next) => {
      const answer = window.confirm('确定离开吗?');
      next(answer); // 用户确认后离开
    });
  }
};

三、动态路由匹配

1. 动态参数(:id
// 路由配置
{ path: '/user/:id', component: User }

// 组件中获取参数
// 模板中:{{ $route.params.id }}
// 组合式 API:const { id } = useRoute().params;
2. 参数作为 Props

通过 props: true 将参数传递给组件:

{ path: '/user/:id', component: User, props: true }

// User 组件中接收 props
export default {
  props: ['id']
};

四、嵌套路由

1. 配置子路由

使用 children 属性定义嵌套路由:

const routes = [
  {
    path: '/user',
    component: UserLayout,
    children: [
      { path: '', component: Profile }, // /user
      { path: 'posts', component: Posts } // /user/posts
    ]
  }
];
2. 父组件中渲染子路由

在父组件模板中添加 <router-view>

<!-- UserLayout.vue -->
<template>
  <div>
    <h1>用户页面</h1>
    <router-view></router-view> <!-- 子路由在此渲染 -->
  </div>
</template>

五、命名路由与命名视图

1. 命名路由

通过 name 标识路由,便于编程式导航:

// 路由配置
{ path: '/settings', name: 'Settings', component: Settings }

// 跳转时使用名称
router.push({ name: 'Settings' });
2. 命名视图

同一页面渲染多个视图:

<!-- App.vue -->
<template>
  <router-view name="header"></router-view>
  <router-view></router-view> <!-- 默认视图 -->
  <router-view name="footer"></router-view>
</template>

// 路由配置
{
  path: '/dashboard',
  components: {
    default: Dashboard,
    header: DashboardHeader,
    footer: DashboardFooter
  }
}

六、编程式导航

1. 基本跳转
// 字符串路径
router.push('/about');

// 对象形式
router.push({ path: '/about' });

// 命名路由
router.push({ name: 'About' });

// 替换当前历史记录(无后退)
router.replace('/login');

// 前进/后退
router.go(1); // 前进一步
router.go(-2); // 后退两步
2. 传递参数
// 路径参数
router.push({ name: 'User', params: { id: 123 } });

// 查询参数
router.push({ path: '/user', query: { name: 'Alice' } });

七、路由懒加载

使用动态导入 (import()) 实现按需加载:

const routes = [
  {
    path: '/about',
    component: () => import('../views/About.vue') // 懒加载
  }
];

八、路由元信息

通过 meta 字段存储额外信息(如页面权限):

{
  path: '/admin',
  component: Admin,
  meta: { requiresAuth: true }
}

九、错误处理(404页面)

配置通配符路由捕获未匹配路径:

{ path: '/:pathMatch(.*)*', component: NotFound }

十、过渡动效

为路由切换添加动画:

<template>
  <router-view v-slot="{ Component }">
    <transition name="fade" mode="out-in">
      <component :is="Component" />
    </transition>
  </router-view>
</template>

<style>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>

总结

核心功能实现方式
路由配置createRouter + routes 数组
导航守卫beforeEachbeforeEnter、组件内守卫
动态路由path: '/user/:id' + $route.paramsprops
嵌套路由children 属性 + 父组件 <router-view>
编程式导航router.pushrouter.replace
路由懒加载component: () => import('...')
路由元信息meta 字段 + 导航守卫校验
过渡动效<transition> 包裹 <router-view>

通过灵活运用这些功能,可以构建复杂且高效的单页面应用(SPA)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值