Vue Router 基础笔记 | 青训营笔记

46 阅读2分钟

这是我参与「第五届青训营」伴学笔记创作活动的第 19 天,今天在开发青训营大项目的过程中,学习了 Vue Router 的使用。

Vue Router 简介

官方文档:介绍 | Vue Router (vuejs.org)

Vue Router 是 Vue.js 的官方路由,可以帮助我们更加方便地构建单页面应用。

安装到 Vue 项目

使用 npm 安装:

npm install vue-router@4

在 Vue 项目中配置

src 目录创建 router 文件夹,在文件夹内创建 index.js 文件,在文件中配置路由选项(或者在其他地方配置路由选项,之后再在 main.js 中导入相应的文件即可):

首先从 vue-router 导入 createRoutercreateWebHistory

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

然后使用 createRouter 创建一个路由配置项:

在配置项中,使用 history: createWebHistory() 配置路由模式,使用 routes 配置具体的路由路径。

routes 为一个数组,每个数组元素为一个路由项。

路由项为一个对象,包含常见的如下属性:

  • path:路由项的路径
  • name:路由项的名称
  • component:路由项的对应的组件
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/home.vue')
    },
  ]
})

最后将路由配置项默认导出,供 main.js 使用:

export default router

main.js 中配置:

import router from './router'

const app = createApp(App) // 原有的

app.use(router)

在模板中使用路由

在模板中使用 router-link 组件定义路由的链接,通过 to 属性指定路由链接的地址:

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

在模板中使用 router-view 组件定义路由内容的显示位置。路由匹配的组件会渲染在这个位置。

<router-view></router-view>

动态路由

在路由项的 path 配置里,使用 :id 表示动态字段。动态字段会匹配任何文字。

const routes = [
  // 动态字段以冒号开始
  { path: '/users/:id', component: User },
]

例如,上述的 path 会匹配 /users/johnny/users/jolyne 等路径。

在 JavaScript 中使用 this.$route.params 可以访问动态字段的名称和内容。

嵌套路由

在路由项的 children 配置里,可以配置子路由项。子路由项会被渲染在父路由的 component 组件内的 <router-view> 组件内。

const routes = [
  {
    path: '/user/:id',
    component: User,
    children: [
      {
        ///user/:id/profile 匹配成功
        // UserProfile 将被渲染到 User<router-view> 内部
        path: 'profile',
        component: UserProfile,
      },
      {
        ///user/:id/posts 匹配成功
        // UserPosts 将被渲染到 User<router-view> 内部
        path: 'posts',
        component: UserPosts,
      },
    ],
  },
]