Vue-router传参

前言

之前都有用过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了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值