常见场景:点击列表详情,跳转到详情内页,传递id参数获取详情数据。
我们先来看看路由跳转的几种方式:
1、通过params方式传参
通过$route.push的path携带参数方式(路由配置中指定参数)
// 路由配置 { path: '/detail/:id', //若id后面加?代表这个参数是可选的,即使不传id也不会导致页面无法访问 name: 'detail', component: Detail } // 列表中跳转 this.$router.push({ path:`/detail/${id}` }) // 详情页获取参数 this.$route.params.id
注意:这种方式参数是以/id跟在url后,刷新页面后参数不会丢失。
通过$route.push的params传参(路由配置中未指定参数)
// 列表中跳转 this.$router.push({ name:'detail', params:{ id:id } }) // 详情页获取参数 this.$route.params.id
注意:这种方式的传参,必须使用name进行跳转,未在路由配置:id,url后不会显示id,刷新页面后参数会丢失。
2、通过query方式传参
// 路由配置 { path: '/detail', name: 'detail', component: Detail } // 列表中跳转 this.$router.push({ path:'/detail', query:{ id:id } }) // 详情页获取参数 this.$route.query.id
注意:这种方式的参数以?id跟在url后,类似get传参,并且,query必须使用path进行传参。刷新页面后参数不会丢失。
传递的参数是对象或数组
还有一种情况就是,如果通过query方式传递的是对象或数组,在地址栏中会被强制转换成[object Object],刷新后页获取不到对象值。
那么我们可以通过JSON.stringify()方法将参数转换为字符串,在获取参数时通过JSON.parse转换成对象。
let parObj = JSON.stringify(obj) // 路由跳转 this.$router.push({ path:'/detail', query:{ obj:parObj } }) // 详情页获取参数 JSON.parse(this.$route.query.obj)
注意:这样虽然可以传对象,但是如果数据多的话地址栏会很长(不太推荐)。
3、使用props配合组件路由解耦
路由配置中指定参数:id
// 路由配置 { path:'/detail/:id', name:'detail', component:Detail, props:true // 如果props设置为true,$route.params将被设置为组件属性 } // 路由跳转 this.$router.push({ path:`/detail/${id}` }) // 详情页获取参数 export default { props:['id'], // 将路由中传递的参数id解耦到组件的props属性上 mounted(){ console.log("id",this.id); } }
路由配置中未指定参数:id
// 路由配置 { path:'/detail', name:'detail', component:Detail, props:true // 如果props设置为true,$route.params将被设置为组件属性 } // 路由跳转 this.$router.push({ name:'detail', params:{ order:{ id:'123456789', name:'商品名称' } } }) // 详情页获取参数 export default { props:['order'], // 将路由中传递的参数order解耦到组件的props属性上 mounted(){ console.log("order",this.order); } }
注意:路由配置中指定参数:id的,页面刷新后参数不会丢失,在路由配置未指定参数的,使用params跳转传参,页面刷新后参数会丢失。
此外,数据量比较大的参数,可以使用sessionStorage或localStorage来进行存储参数来解决页面刷新参数丢失的问题,具体结合实际项目即可。