在单页面应用(SPA)的开发中,路由不仅仅是页面的导航工具,更是实现组件间数据传递的重要桥梁。Vue Router 作为 Vue.js 的官方路由管理器,提供了灵活的路由传参功能,使得开发者能够轻松地将数据从一个页面传递到另一个页面,增强了应用的交互性与用户体验。
本文将深入探讨 Vue Router 中的路由传参机制,包括动态路由参数和查询参数的使用。我们将详细讲解如何在路由中定义参数、如何在组件中获取这些参数,以及如何将参数传递给其他路由。通过具体的代码示例,我们将展示如何在实际开发中灵活运用路由传参,从而实现更复杂的页面交互和数据展示。
在过去,我们习惯使用 route.params
来获取路由传递的参数,尽管这种方式有效,但它让组件与路由配置紧密耦合,影响了组件的复用性。本节将探讨一种更为灵活的路由传参方式——使用属性的方式进行参数传递。
还记得我们编写的用户设置页面是如何获取路由传递的 id
参数的吗?代码如下:
<template>
<h1>用户设置</h1>
<h2>id: {{ $route.params.id }}</h2>
</template>
<script>
export default {
name: 'UserSetting'
}
</script>
由于在组件的模板内部直接使用了 $route
属性,这导致该组件的通用性大大降低。我们可以通过属性传递参数来增强组件的复用性。
首先,将组件中所有耦合路由的部分去除掉,修改如下:
<script setup>
defineProps(['id'])
</script>
<template>
<h1>用户设置</h1>
<h2>id: {{ id }}</h2>
</template>
现在,UserSetting
组件能够通过外部传递的属性来实现内部逻辑。接下来,我们需要将路由的传参映射到外部属性上。
Vue Router 默认支持属性传递功能。在定义路由时,将 props
设置为 true
,则路由中传递的参数会自动映射到组件定义的外部属性。代码如下:
const routes = [
{
path: '/user/:id(\\d+)',
component: UserSetting,
props: true // 将路由参数映射为组件的 props
}
];
这样,路由参数会自动传递到 UserSetting
组件的 id
属性中。
高级配置
对于有多个页面出口的同级命名视图,我们需要对每个视图的 props
单独进行设置,示例如下:
const routes = [
{
path: '/home/:username/:id',
components: {
topBar: User,
default: UserSetting
},
props: {
topBar: true,
default: true
}
}
];
如果组件内部需要的参数与路由本身并没有直接关系,我们也可以将 props
设置为对象,此时 props
设置的数据将原样传递给组件的外部属性。例如:
const routes = [
{
path: '/user/:id(\\d+)',
component: UserSetting,
props: { id: '000' } // 固定传递 id 属性为 '000'
}
];
此时路由中的 id
参数将被弃用,组件中获取到的 id
属性值将固定为 “000”。
props
还有一种更便捷的使用方式,可以直接将其设置为一个函数,函数返回要传递到组件的外部属性对象,这种方式动态性很好,示例如下:
const routes = [
{
path: '/user/:id(\\d+)',
component: UserSetting,
props: route => {
return {
id: route.params.id,
other: 'other'
};
}
}
];
这种方式可以根据路由参数动态生成传递给组件的属性。
$route.params
,会导致组件与路由耦合。defineProps
和 props
映射路由参数,使组件更加通用和可复用。props
。