前言
之前都有用过vue-router,也传过参,但是都是看过文档之后直接用,没有具体了解过到底传参有哪几种方法,那么今天就来总结一下。
URL传参
这种方式可以直接在URL里面添加参数传过去
//router-link跳转
<router-link :to={path:`/son/${id}`}></router-link>
//js跳转
goto(id){
this.$router.push({
path: `/son/${id}`
});
}
//路由配置
{
path:'/son',
component: son
}
//子组件取参数
this.$route.params.id
params传参
//router-link
<router-link :to{name:'son',params:{id:id}}></router-link>
//js跳转
this.$router.push({
name: 'son',
params: {
id:id
}
})
//路由配置
{
path: '/son',
name: son,
components: son
}
//取参数
this.$route.params.id
tips:如果使用params传参,需要用name来匹配路由,而不可以通过path
tips:需要注意的是,params传参在刷新的时候会失去参数,且如果如果在当前页面继续跳转当前页面,并不会成功,例如,路径已经是/son
了,如果此时再跳转到/son
那么新传入的参数将不会生效,如果是通过router-link
跳转的什么也不会发生,如果是通过js跳转的将会报错
如果不想在控制台出现这个报错,可以catch他,又或者是检测要跳转的路径是否与当前路径相同
//catch
this.$router.push({
name: '/son',
params: {
id:id
}
}).catch((e) => {
})
//检测
const path = `/son/${id}`
if ($route.path !== path) this.$router.push(path)
如果又想使用param传参,又想避免上面的问题,那么可以将路由中的路径改成path:'/son/:id'
,但是这样子就会在URL中显示出参数
query传参
//router-link
<router-link :to="path:'/son',query={id:id}"></router-link>
//js
this.$router.push({
path: '/son',
query: {
id:id
}
})
//路由
{
path:'/son',
name:'son',
components: son
}
//获取
this.$route.query.id
query
可以通过name
或者path
匹配路由,使用query传参的话,会在URL后面出现?id=XXX
通过props解耦
上面取参数的时候都是通过$route
,这就会导致组件只能在特定的URL下使用,那么我们可以通过一些方法,将参数传到props,这样就提高了组件的复用
布尔模式
//组件调用
//路由传递方式只能使用params传递参数
this.$router.push(
name: 'Describe',
params: {
id: id
}
})
//路由配置
{
path: '/describe',
name: 'Describe',
component: Describe,
props: ture
}
//组件获取
const Describe= {
props: ['id'],
template: '<div>User {{ id }}</div>'
}
将props
设置为true
,就可以将$route.params
传递到props
中,这种模式只适用于param
传参,不适用于query
对象模式
当props是静态的时候可以使用对象模式
// 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
//路由配置
{
path: '/describe',
name: 'Describe'
components: Describe
props: { id:"123" }
}
//单文件组件在props中获取
const Describe= {
props: ['id'],
template: '<div>describe{{ id }}</div>'
}
如果跳转的时候也有相同属性名的参数传入,那么路由配置中的静态props
优先级更高
函数模式
//组件调用(这里只能把参数放置在query中)
this.$router.push({
path: '/describe',
query: {
name: name
}
})
//路由设置
{
path: '/describe',
component: describe,
props: (route) => ({ name: route.query.id})
}
这种模式下就可以使用query了