vue实现路由传参
Vue 路由传参的实现方式
在 Vue 中,可以通过路由传参实现组件间的数据传递。以下是常见的几种方法:
使用 params 传参
通过 params 传递参数,参数会显示在 URL 中。需要在路由配置中定义参数名称。
// 路由配置
const routes = [
{
path: '/user/:id',
name: 'User',
component: User
}
]
// 传递参数
this.$router.push({ name: 'User', params: { id: 123 } })
// 接收参数
this.$route.params.id
使用 query 传参
通过 query 传递参数,参数会以键值对的形式显示在 URL 中。
// 传递参数
this.$router.push({ path: '/user', query: { id: 123 } })
// 接收参数
this.$route.query.id
使用 props 传参
在路由配置中启用 props,可以将参数作为组件的 props 传递。
// 路由配置
const routes = [
{
path: '/user/:id',
name: 'User',
component: User,
props: true
}
]
// 组件中接收
export default {
props: ['id']
}
使用编程式导航传参
通过 $router.push 或 $router.replace 方法传递参数。
// 传递 params
this.$router.push({ name: 'User', params: { id: 123 } })
// 传递 query
this.$router.push({ path: '/user', query: { id: 123 } })
动态路由匹配
在路由配置中使用动态路径参数,可以匹配不同的 URL 模式。
const routes = [
{
path: '/user/:id',
component: User
}
]
命名路由传参
通过命名路由传递参数,可以更清晰地管理路由参数。
// 路由配置
const routes = [
{
path: '/user/:id',
name: 'User',
component: User
}
]
// 传递参数
this.$router.push({ name: 'User', params: { id: 123 } })
使用 $route 对象获取参数
在组件中可以通过 $route 对象访问当前路由的参数。
// 获取 params
this.$route.params.id
// 获取 query
this.$route.query.id
以上方法可以根据具体需求选择使用,灵活实现 Vue 路由传参功能。







