Vue路由传参

1. router-link传参

父组件:使用<router-link to="/跳转的路径/传递的参数"></router-link>

例如:<router-link to="/a/123"></router-link>

子组件接收:this.$route.params.num来接收传递过来的参数

mounted(){
this.num=this.$route.params.num
}

路由配置:{path:‘/a/num’,name:A,component:A}

地址栏显示的:http://localhost:8080/#/a/123

2. 使用this.$router.push实现路由传参

父组件:绑定点击事件,编写跳转代码

<button @click="goGame(Math.floor(Math.random() * 999))">去游戏</button>
 goGame (id) {
      this.$router.push({
        path: `/game/${id}`
      })
    },

路由:

    {
      path: '/game/:id',
      name: 'game',
      component: Game
    },

子组件:

  <div>
    <h1>游戏{{id}}</h1>
  </div>
  data () {
    return {
      id: ''
    }
  },
  mounted () {
    this.id = this.$route.params.id
  }
3. 通过路由属性的name匹配路由,在根据params传参

父组件

<button @click="goSheep">去羊村</button>
    goSheep () {
      this.$router.push({
        name: 'sheep',
        params: {
          sheepName: '喜羊羊'
        }
      })
    }

路由:

    {
      path: '/sheep',
      name: 'sheep',
      component: Sheep
    },

子组件:

  <div>
    <h1>我是DJ{{name}}</h1>
  </div>
  data () {
    return {
      name: ''
    }
  },
  mounted () {
    this.name = this.$route.params.sheepName
  }
4. 通过push的path属性进行query属性

父组件

    <button @click="goSchool">query传参</button>
    goSchool () {
      this.$router.push({
        path: '/school',
        query: {
          schoolName: '清华大学'
        }
      })
    }

路由:

    {
      path: '/school',
      name: 'school',
      component: School
    }

子组件

    <h1>这里是{{schoolName}}</h1>  
data () {
    return {
      schoolName: ''
    }
  },
  mounted () {
    this.schoolName = this.$route.query.schoolName
  }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值