返回

Vue Router 常用 API 详解:开启前端路由之旅

前端

前言

在单页面应用 (SPA) 中,路由是必不可少的。它允许用户在页面之间导航,而无需重新加载整个页面。Vue Router 是 Vue.js 官方推荐的前端路由库,它提供了强大的功能和易于使用的 API。

Vue Router 常用 API

1. <router-link> 组件

<router-link> 组件支持用户在具有路由功能的应用中导航。通过 to 属性指定目标地址,默认渲染成带有正确链接的 标签,可以通过配置 tag 属性生成别的标签。另外,当目标路由成功激活时,链接元素自动设置一个表示激活的 CSS 类名。

<router-link to="/about">关于</router-link>

2. $router 对象

$router 对象是 Vue Router 实例,它提供了许多有用的属性和方法,用于管理路由。

// 获取当前路由信息
const currentRoute = this.$router.currentRoute

// 跳转到指定路由
this.$router.push('/about')

// 替换当前路由
this.$router.replace('/about')

// 回到上一页
this.$router.go(-1)

3. $route 对象

$route 对象是当前激活的路由信息,它提供了许多有用的属性,用于获取当前路由的信息。

// 获取当前路由路径
const path = this.$route.path

// 获取当前路由名称
const name = this.$route.name

// 获取当前路由参数
const params = this.$route.params

// 获取当前路由查询参数
const query = this.$route.query

4. 路由导航守卫

路由导航守卫允许您在导航到新路由之前或之后执行某些操作。有三种类型的导航守卫:

  • 全局导航守卫:适用于所有路由
  • 路由独享导航守卫:仅适用于特定路由
  • 组件内导航守卫:仅适用于特定组件
// 全局导航守卫
router.beforeEach((to, from, next) => {
  // ...
})

// 路由独享导航守卫
router.beforeEach((to, from, next) => {
  if (to.name === 'about') {
    // ...
  }
})

// 组件内导航守卫
export default {
  beforeRouteEnter(to, from, next) {
    // ...
  }
}

5. 嵌套路由

嵌套路由允许您在父路由内定义子路由。这对于构建复杂的前端应用非常有用。

const router = new VueRouter({
  routes: [
    {
      path: '/parent',
      component: ParentComponent,
      children: [
        {
          path: 'child',
          component: ChildComponent
        }
      ]
    }
  ]
})

结语

Vue Router 是一个功能强大且易于使用的前端路由库。本文介绍了 Vue Router 的常用 API,帮助您轻松开启前端路由之旅。如果您想了解更多关于 Vue Router 的内容,可以访问官方文档:https://router.vuejs.org/