Vue3 中运用 Router 路由实现跳转传参的方法

2025-01-10 20:14:42   小编

Vue3 中运用 Router 路由实现跳转传参的方法

在 Vue3 开发中,使用 Router 路由实现页面跳转并传递参数是常见需求。合理运用路由传参能使页面间的数据交互更流畅,提升应用的用户体验。本文将详细介绍 Vue3 中运用 Router 路由实现跳转传参的方法。

1. 动态路由参数

动态路由参数是在路由路径中定义参数,通过这种方式可以将特定信息传递到目标页面。在 router/index.js 文件中定义路由时设置动态参数。例如:

const routes = [
  {
    path: '/user/:id',
    name: 'User',
    component: () => import('@/views/User.vue')
  }
];

这里的 :id 就是动态参数。在跳转时,可以这样写:

<router - link :to="`/user/${userId}`">查看用户</router - link>

在目标组件 User.vue 中,可以通过 $route 对象获取参数:

export default {
  setup() {
    const route = useRoute();
    const userId = route.params.id;
    console.log(userId);
  }
};

2. query 参数

query 参数以查询字符串的形式附加在 URL 后面。定义路由时无需特殊设置。在跳转时传递参数:

<router - link :to="{ path: '/home', query: { name: '张三', age: 25 } }">跳转到主页</router - link>

在目标组件中获取参数:

export default {
  setup() {
    const route = useRoute();
    const name = route.query.name;
    const age = route.query.age;
    console.log(name, age);
  }
};

query 参数的优点是传递的数据会显示在 URL 中,方便调试,但安全性相对较低,不适合传递敏感信息。

3. 路由守卫传参

路由守卫可以在路由切换前、切换后等阶段进行一些操作,也可以用来传参。例如,在 router/index.js 中使用 beforeEach 守卫:

router.beforeEach((to, from, next) => {
  to.meta.userId = '123';
  next();
});

在目标组件中获取参数:

export default {
  setup() {
    const route = useRoute();
    const userId = route.meta.userId;
    console.log(userId);
  }
};

掌握 Vue3 中 Router 路由跳转传参的这些方法,能在开发中更高效地实现页面间的数据传递,满足各种业务需求,打造功能更强大、交互更流畅的应用程序。

TAGS: Vue3 Router路由 跳转传参 Vue3路由跳转传参

欢迎使用万千站长工具!

Welcome to www.zzTool.com