Vue3——Router路由语法简介和使用

Vue 3中的路由管理通过Vue Router实现,Vue Router允许开发者在单页面应用中实现路由的管理和导航。

1. 简介

  • Vue Router是Vue.js官方的路由管理器,用于实现单页面应用的路由功能。
  • 可以将不同的组件映射到不同的路由,实现页面间的切换而不刷新整个页面。
  • 支持嵌套路由、路由参数、路由导航守卫等功能。

2. 基本使用语法

a. 安装Vue Router

npm install vue-router@next

b. 创建并配置Router实例

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

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

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

c. 注入Router实例

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

   const app = createApp(App);
   app.use(router);
   app.mount('#app');

d. 在组件中使用Router

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

       <router-view></router-view>
     </div>
   </template>

e. 路由参数

   const routes = [
     { path: '/user/:id', component: User }
   ];

f. 嵌套路由

const routes = [
     {
       path: '/user',
       component: UserLayout,
       children: [
         { path: 'profile', component: UserProfile },
         { path: 'settings', component: UserSettings }
       ]
     }
   ];

g. 路由导航守卫

router.beforeEach((to, from, next) => {
     // 在路由跳转前执行逻辑
     next();
   });

   router.afterEach((to, from) => {
     // 在路由跳转后执行逻辑
   });

当使用Vue Router进行路由管理时,除了基本的路由配置外,还有一些小细节问题需要考虑,如路由重定向、路由传参、动态路由匹配等。

1. 路由重定向

  • 路由重定向可以在用户访问某个路由时自动重定向到另一个路由。
  • 可以通过 redirect 属性进行路由重定向的配置。
const routes = [
     { path: '/home', component: Home },
     { path: '/about', component: About },
     { path: '/', redirect: '/home' }
   ];

2. 路由传参

  • 可以通过路由参数传递数据给目标组件。
  • 使用路由参数时,需要在路由配置中定义参数的名称。
const routes = [
     { path: '/user/:id', component: User }
   ];

   // 在组件中通过$route.params访问路由参数
   export default {
     mounted() {
       console.log(this.$route.params.id);
     }
   };

3. 动态路由匹配

  • 动态路由匹配允许在路由配置中使用通配符来匹配多个路由。
  • 通配符可以是 * (匹配所有)或 : (匹配部分)。
const routes = [
     { path: '/user/:id', component: User },
     { path: '/user/*', component: UserList }
   ];

4. 路由导航守卫

  • 路由导航守卫允许在路由跳转前后执行一些逻辑。
  • 包括 beforeEach 、 beforeResolve 、 afterEach 等守卫。
router.beforeEach((to, from, next) => {
     // 在路由跳转前执行逻辑
     next();
   });

   router.afterEach((to, from) => {
     // 在路由跳转后执行逻辑
   });

5. 命名路由

  • 可以给路由配置起一个名字,方便在代码中引用。
  • 使用 name 属性为路由配置指定名称。
const routes = [
     { path: '/home', component: Home, name: 'home' },
     { path: '/about', component: About, name: 'about' }
   ];

   // 在代码中使用命名路由
   this.$router.push({ name: 'home' });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值