面试题:Vue 路由之间是如何跳转的?有哪些跳转方式?

在 Vue 中,路由跳转是 Vue Router 的核心功能之一。Vue Router 提供了多种方式来实现路由之间的跳转,以下是常见的跳转方式:


1. 声明式导航

使用 <router-link> 组件实现路由跳转,适合在模板中使用。

示例:

<template>
  <div>
    <!-- 跳转到指定路径 -->
    <router-link to="/home">Home</router-link>
    <!-- 跳转到命名路由 -->
    <router-link :to="{ name: 'about' }">About</router-link>
    <!-- 带参数的跳转 -->
    <router-link :to="{ name: 'user', params: { id: 123 } }">User</router-link>
  </div>
</template>

特点:

  • 类似于 <a> 标签,但不会触发页面刷新。
  • 适合在模板中直接使用。

2. 编程式导航

通过 JavaScript 代码实现路由跳转,适合在组件逻辑中使用。

常用方法:

  • this.$router.push():跳转到指定路由,会向历史记录中添加一条记录。
  • this.$router.replace():跳转到指定路由,但不会向历史记录中添加记录(替换当前记录)。
  • this.$router.go():在历史记录中前进或后退。

示例:

export default {
  methods: {
    goToHome() {
      // 跳转到指定路径
      this.$router.push('/home');
    },
    goToAbout() {
      // 跳转到命名路由
      this.$router.push({ name: 'about' });
    },
    goToUser() {
      // 带参数的跳转
      this.$router.push({ name: 'user', params: { id: 123 } });
    },
    replaceHome() {
      // 替换当前路由
      this.$router.replace('/home');
    },
    goBack() {
      // 返回上一页
      this.$router.go(-1);
    }
  }
}

特点:

  • 适合在事件处理或异步操作后跳转。
  • 更灵活,可以在 JavaScript 中动态控制路由。

3. 路由传参

在跳转路由时,可以通过以下方式传递参数:

(1)动态路由参数

在路由配置中定义动态参数,通过 params 传递。

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

// 跳转时传递参数
this.$router.push({ name: 'user', params: { id: 123 } });

(2)查询参数

通过 query 传递查询参数。

// 跳转时传递查询参数
this.$router.push({ path: '/user', query: { id: 123 } });

// 目标路由中获取参数
this.$route.query.id; // 123

(3)Props 传参

在路由配置中启用 props,将路由参数作为组件的 props 传递。

// 路由配置
const routes = [
  { path: '/user/:id', component: User, props: true }
];

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

4. 导航守卫

在路由跳转前后,可以通过导航守卫进行拦截或处理逻辑。

常用导航守卫:

  • 全局前置守卫router.beforeEach
  • 全局解析守卫router.beforeResolve
  • 全局后置钩子router.afterEach
  • 路由独享守卫beforeEnter
  • 组件内守卫beforeRouteEnterbeforeRouteUpdatebeforeRouteLeave

示例:

router.beforeEach((to, from, next) => {
  if (to.path === '/restricted') {
    next('/login'); // 重定向到登录页
  } else {
    next(); // 允许跳转
  }
});

5. 重定向

在路由配置中,可以通过 redirect 实现路由重定向。

示例:

const routes = [
  { path: '/', redirect: '/home' }, // 访问根路径时重定向到 /home
  { path: '/home', component: Home }
];

6. 别名

在路由配置中,可以通过 alias 为路由设置别名。

示例:

const routes = [
  { path: '/home', component: Home, alias: '/welcome' } // 访问 /welcome 时渲染 Home 组件
];

总结

Vue 路由跳转的常见方式包括:

  1. 声明式导航:使用 <router-link>
  2. 编程式导航:使用 this.$router.push()this.$router.replace() 等。
  3. 路由传参:通过 paramsqueryprops 传递参数。
  4. 导航守卫:在跳转前后进行拦截或处理逻辑。
  5. 重定向:通过 redirect 实现路由重定向。
  6. 别名:通过 alias 设置路由别名。

在实际开发中,通常结合多种方式来实现灵活的路由跳转和导航控制。

THE END
点赞15 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容