# 参数传递
# 概述
我们经常需要把某种模式匹配到的所有路由,全都映射到同个组件。例如,我们有一个 User 组件,对于所有 ID 各不相同的用户,都要使用这个组件来渲染。此时我们就需要传递参数了;
# 使用路径匹配的方式
# 修改路由配置
{path: '/user/profile/:id', name:'UserProfile', component: UserProfile}
1
说明:主要是在 path
属性中增加了 :id
这样的占位符
# 传递参数
# router-link
<router-link :to="{name: 'UserProfile', params: {id: 1}}">个人信息</router-link>
1
说明:此时我们将 to
改为了 :to
,是为了将这一属性当成对象使用,注意 router-link 中的 name 属性名称 一定要和 路由中的 name 属性名称 匹配,因为这样 Vue 才能找到对应的路由路径;
# 代码方式
this.$router.push({ name: 'UserProfile', params: {id: 1}});
1
# 接收参数
在目标组件中使用
{{ $route.params.id }}
1
来接收参数
# 使用 props
的方式
# 修改路由配置
{path: '/user/profile/:id', name:'UserProfile', component: UserProfile, props: true}
1
说明:主要增加了 props: true
属性
# 传递参数
同上
# 接收参数
为目标组件增加 props
属性,代码如下:
export default {
props: ['id'],
name: "UserProfile"
}
1
2
3
4
2
3
4
模板中使用
{{ id }}
1
接收参数