路由动态传参

9 篇文章 0 订阅

 

从列表页跳到编辑页时,经常需要传参。我比较常用的有下面两种:

一、刷新后失效

路由定义:

{
    path: '/test',
    name: 'test',
    component: () => import('../views/Test.vue'),
    meta: {title:'', breadNumber: 1}
  }

路由跳转:

this.$router.push({
    name: 'test',
    params: {
        id: this.id
    }
})

组件中取参:

this.$route.params.id

以上这种方式,不会把id暴露在url中。但是,刷新页面后就取不到这个id了。

二、刷新后不失效

1.路由定义中带动态参数

路由定义:

{    
    path: '/test/:id',
    name: 'test',
    component: () => import('../views/Test.vue'),
    meta: {title:'', breadNumber: 1},
    props: true
}

路由跳转:

            this.$router.push({
                // name: 'test',
                // params: { 
                //     id: this.id
                // }
                path: `/test/${this.id}`
            })

Test.vue组件中取参:

this.$route.params.id

或者

this.id (这是因为在路由定义时设置了props:true)

以上这种方式会有个问题,当路由跳转时,如果this.id取不到值,跳不到/test下。解决办法是,在定义路由时,增加如下路由定义:

{    
    path: '/test/:id',
    name: 'test',
    component: () => import('../views/Test.vue'),
    meta: {title:'', breadNumber: 1},
    props: true
},
{   //这部分是新增的
    path: '/test',
    name: 'test',
    component: () => import('../views/Test.vue'),
    meta: {title:'', breadNumber: 1},
    props: true
}

(这种方法感觉代码太重复,但是我目前没找到更好的办法。如果您有更好的办法,请告知,谢谢!)

2.路由定义中不带参数,路由跳转后 url 会带 "?id=xxx"

路由定义:

{    
    path: '/test',
    name: 'test',
    component: () => import('../views/Test.vue'),
    meta: {title:'', breadNumber: 1}
}

路由跳转:

this.$router.push({
    path: '/test',
    query: {
        id: this.id
    }
})

组件取参:

this.$route.query.id

 

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值