1.动态路由传参
在路由配置path中添加/:id来对应 $router.push 中path携带的参数,参数会显示在url中 刷新后不会消失
// 对应的路由配置
{
path: '/home/test/:id?/:name?',
name: 'RouterTest',
component: () => import('@/views/home/test/index.vue')
}
// 路由跳转前
this.$router.push({
path: 'test/123/Li'
})
// 跳转后
export default {
created () {
window.console.log(this.$route.params.id) // 123
window.console.log(this.$route.params.name) // Li
}
}
2.query传参
使用path
来匹配路由,然后通过query来传递参数,跳转后的路由用this.$route.query
接收传递过来的参数,传递的参数会显示在url后面?,页面刷新后不会消失
// 对应的路由配置
{
path: '/home/test/',
name: 'RouterTest',
component: () => import('@/views/home/test/index.vue')
}
// 跳转前
this.$router.push({
path: 'test/',
query: {
id: 123,
name: 'Li'
}
})
// 第二种写法
// this.$router.push('test/?id=123&name=Li')
// 跳转后
export default {
created () {
window.console.log(this.$route.query.id) // 123
window.console.log(this.$route.query.name) // Li
}
}
3.params传参
通过路由属性中的name
来确定匹配的路由,通过params来传递参数,跳转后的路由用this.$route.params
接收传递过来的参数。参数会显示在url中,页面刷新后会消失
// 对应的路由配置
{
path: '/home/test/',
name: 'RouterTest',
component: () => import('@/views/home/test/index.vue')
}
// 跳转前
this.$router.push({
name: 'RouterTest',
params: {
id: 123,
name: 'Li'
}
})
// 第二种写法
// this.$router.push('test/?id=123&name=Li')
// 跳转后
export default {
created () {
window.console.log(this.$route.params.id) // 123
window.console.log(this.$route.params.name) // Li
}
}
总结
传参方式 | 配置 | 特点 |
---|---|---|
动态路由传参 | 路由配置的path中添加/:id | 参数会显示在url中 刷新后不会消失 |
query传参 | 使用path来匹配路由 | 参数会显示在url中 刷新后不会消失 |
params传参 | 使用路由属性中的name来确定匹配的路由 | 参数不会显示在url中 刷新后会消失 |