vue(四) -----路由传参

使用案例

路由配置:

const routes = [
    {
        path:'/a',
        name:'a',
        component:()=>import('@/components/aCom.vue')
    },
    {
        path:'/b',
        name:'b',
        component:()=>import('@/components/bCom.vue')
    }
]

父组件,两个按钮实现组件的跳转,实现路由切换,并传递参数

<template>
  <div id="app">
    <button @click = 'ToA'>a组件</button>
    <button @click = 'ToB'>b组件</button>
    <router-view></router-view>
  </div>
</template>
<script>

export default {
  name: 'App',
  methods:{
    ToA(){
      this.$router.push({
        name:'a',
        // path:'/a',
        query:{
          id:'a'
        }
      })
    },

    ToB(){
      this.$router.push({
        name:'b',
        // path:'/b',
        query:{
          id:'b'
        }
      })
    },
  }
}
</script>

query

query传递参数的特点:

  1. 参数会以url字符串序列的方式拼接到url后面,如 http://localhost:8080/a?id=a ,其中 http://localhost:8080/a 是url,id=a是我们传递过来的参数。
  2. 可以使用path,也可以使用name
  3. 参数一定会显示在url中
  4. 页面刷新后,参数仍然存在
      this.$router.push({
        name:'a',
        // path:'/a',
        query:{
          id:'a'
        }
      })

在这里插入图片描述
使用this.route.query.id可以获取到我们刚才路由传过来的id
在这里插入图片描述
这两个地方的名称必须相同

params

params传参可以分为显示和不显示两种

不显示

特点:

  1. 参数不会显示在url中,如http://localhost:8080/b
  2. 可以使用path,也可以使用name
  3. 页面刷新后,参数不存在
      this.$router.push({
        // name:'a',
        path:'/a',
        params:{
          id:'a'
        }
      })

显示

特点:

  1. routers中的url需要使用占位符,占位路由中的数据位置,以供显示
  2. 参数不会显示在url中,如http://localhost:8080/b/b
  3. 可以使用name,不可以使用path
  4. 页面刷新后,参数仍存在

路由重新设置:

const routes = [
    {
        path:'/a/:id',
        name:'a',
        component:()=>import('@/components/aCom.vue')
    },
    {
        path:'/b/:id',
        name:'b',
        component:()=>import('@/components/bCom.vue')
    }
]

编程式路由:

      this.$router.push({
        name:'a',
        params:{
          id:'a'
        }
      })
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值