vue-router 路由跳转:
看这个路由配置:
{
path: '/set/list/:id/:age', // 使用动态路径参数来接收 id 和 age
name: 'setList',
components: () => import("@/views/set/List"),
meta: {
title: '设置',
keepAlive: true,
}
}
name配对params
,path配对query
命名路由name 搭配 params,刷新页面,参数会丢失
路由path 搭配 query,刷新页面,数据不会丢失
接收参数,使用 this.$route.params、this.$route.query,就能获取到参数的值
this.$router.push({
name: 'setList',
params: {
id: '123',
age: 100
}
})
// 另一个页面接收:this.$route.params.id
// 地址栏中会显示类似的路径:/set/List/123/100
this.$router.push({
path: '/set/List',
query: {
id: '123',
age: 100
}
})
// 另一个页面接收:this.$route.query.id
// 地址栏中会显示类似的路径:/set/List?id=123&age=100
另:
1、query
相当于GET请求,页面跳转时,参数显示在地址栏
2、params
相当于POST请求,页面跳转时,参数不会显示在地址中
3、使用path
跳转路由时,path会忽略params
因为,path已经定义了具体的路由路径,
这意味着如果你尝试同时使用 path 和 params,params的值将会被忽略,并且在跳转时不会传递给目标组件。
所以,path和params不能一起使用,
所以,推荐使用name和query的方式
路由配置项path 没有定义动态段的情况
{
path: '/set/list'
name: 'setList',
components: () => import("@/views/set/List"),
meta: {
title: '设置',
keepAlive: true,
}
}
VueRouter中,当使用name和params进行路由跳转时,通过this.$route.params是不能直接获取参数的,
this.$route.params
主要用于获取,路由动态段,定义的参数,
在这个路由配置中,路径/set/list并没有定义动态段
,所以,this.$route.params将会是undefined
,
如果你希望通过name进行路由跳转并传递参数
,你应该使用query
而不是params,
修改后的代码:
this.$router.push({
name: 'setList',
query: {
id: '123',
age: 100
}
})
// 在目标组件中,你可以使用 this.$route.query 获取查询参数
console.log(this.$route.query.id) // 输出 '123'
console.log(this.$route.query.age) // 输出 '100'