Skip to content

路由传参方式

面试题:Vue 项目中前端路由传参方式有哪些?

  1. 路径参数
  2. 查询参数
  3. 路由状态参数
  4. 路由 props 参数

1. 路径参数

通过 params 获取路径参数

js
const routes = [
  {
    path: "/users/:userId(\\d+)",
    component: User,
  },
];
js
// vue2
this.$route.params.userId;
// vue3
const route = useRoute();
const id = route.params.id;

2. 查询参数

通过 URL 中的查询字符串传递的参数,以 ?key=value 的形式进行传递。

特点:可以传递多组参数

js
// 使用 this.$router.push 传递查询参数
this.$router.push({ path: "/user", query: { id: "123" } });

// 获取参数
this.$route.query.id;

3. 路由状态参数

路由状态参数(Route State Parameters)是一种通过 router.push 或 router.replace 方法传递的参数,这些参数不会在 URL 中显示,而是在应用程序的内存中进行传递,此方式适合传递一些不希望在 URL 中公开显示的临时数据或敏感信息。

js
// 传递状态参数
this.$router.push({ path: "/user", state: { id: "123" } });

// 获取参数
history.state.id;

4. 路由 props 参数

在路由配置中设置 props: true 或传递一个函数,将路由的 params 或 query 直接作为组件的 props 传递给子组件。

js
const routes = [
  {
    path: "/user/:id",
    component: User,
    props: true,
  },
];
vue
<script setup>
  defineProps({
    id: {
      // ....
    },
  });
</script>

Vue3 课程《细节补充 - 路由组件传参》

参考答案:

Vue 项目中前端路由传参的方式主要有这么几种:

  1. 路径参数: 这种方式直观,路径直接反映参数的结构。适合用于需要在路径中明确表示的参数,如资源 ID。
  2. 查询参数:该方式可选参数使用方便,适合用于不确定的参数个数,或者需要在组件间传递较多的参数。
  3. 路由状态参数:参数不会出现在 URL 中,安全性更高,适合用于敏感信息的传递。
  4. 路由 props 参数:参数直接以 props 形式传入,这样能删除组件对 $route 的直接依赖,达到与 $route 解耦的效果。

Released under the MIT License.