Skip to content

路由

Vue Router 是 Vue.js 的官方路由。它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得轻而易举。功能包括:

  • 嵌套路由映射
  • 动态路由选择
  • 模块化、基于组件的路由配置
  • 路由参数、查询、通配符
  • 展示由 Vue.js 的过渡系统提供的过渡效果
  • 细致的导航控制
  • 自动激活 CSS 类的链接
  • HTML5 history 模式或 hash 模式
  • 可定制的滚动行为
  • URL 的正确编码

1.基本使用

1.1 安装

对于一个现有的使用 JavaScript 包管理器的项目,你可以从 npm registry 中安装 Vue Router:

bash
npm install vue-router@4

如果你打算启动一个新项目,你可能会发现使用 create-vue 这个脚手架工具更容易,它能创建一个基于 Vite 的项目,并包含加入 Vue Router 的选项:

bash
npm create vue@latest

你需要回答一些关于你想创建的项目类型的问题。如果您选择安装 Vue Router,示例应用还将演示 Vue Router 的一些核心特性。

使用包管理器的项目通常会使用 ES 模块来访问 Vue Router,例如 import { createRouter } from 'vue-router'

1.2 使用步骤

要使用路由,以下是基本步骤

1.2.1 配置路由

js
import { createMemoryHistory, createRouter } from 'vue-router'

import HomeView from './HomeView.vue'
import AboutView from './AboutView.vue'

const routes = [
  { path: '/', component: HomeView },
  { path: '/about', component: AboutView },
]

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

export default router

解释:

  • createRouter:用于创建路由实例
  • createMemoryHistory:用于创建Memory路由模式
  • routes:路由信息表,当我们主动跳转路由时,会根据对应的路径切换相应的组件

1.2.2 注册路由

引入上方的router.js文件,并使用app.use()函数注册router这个插件

js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)

app.use(router)
app.mount('#app')

和大多数的 Vue 插件一样,use() 需要在 mount() 之前调用。

注册router插件主要做了一下几件事

  1. 全局注册 RouterViewRouterLink 组件。
  2. 添加全局 $router$route 属性。
  3. 启用 useRouter()useRoute() 组合式函数。
  4. 触发路由器解析初始路由。

1.2.3 使用路由

在我们需要使用路由的地方,使用RouterLink组件跳转路由,RouterView 组件用来显示路由组件

vue
<template>
  <p>
    <strong>Current route path:</strong> {{ $route.fullPath }}
  </p>
  <nav>
    <RouterLink to="/">Go to Home</RouterLink>
    <RouterLink to="/about">Go to About</RouterLink>
  </nav>
  <main>
    <RouterView />
  </main>
</template>

解释:

  • RouterLink:一个特殊的a标签(最后会被解析为a标签),组件有个to属性,其值为一个字符串类型的路径,这个值对应着router.jsroutes里的path,点击这个组件,RouterView的内容会自动切换为path对应的component,这样的也叫做声明式导航
  • RouterView:用来显示路由页面,当点击RouterLink时,会根据RouterLinkto属性切换成不同的component组件
  • $route:当前路由的详情信息,同vue2

MIT Licensed