路由传参的方式【详解举例说明】

前言

路由传参可以通过声明式导航router-link:to="..."和编程式导航router.push(…)这两者来传参,不过本篇文章主要介绍前者的传参方法

Vue-router 传递参数

1. 使用name

在路由文件的/index.js配置name属性

routes: [
    {
      path: '/',
      name: 'Ting',
      component: Ting
    }
]

在模板src/App.vue中用$route.name来接收 比如:<p>{{ $route.name}}</p>

2. 通过to

格式:

<router-link :to="{name:xxx,params:{属性名:属性值}}">valueString</router-link>

在App.vue文件中

<router-link :to="{name:'Ting',params:{age:18}">Ting</router-link>

在src/router/index.js配置该页面的路由

{path:'/ting',name:'Ting',component:Ting}

在模板里(src/components/Ting.vue)用$route.params.属性名来接受参数.

{{$route.params.age}}

3. 通过path匹配路由,通过query传递参数

<router-link :to="{ name:'Ting',query: { age: 18}}" >
    我跳跳跳 --- 
</router-link>

配置相对应的路由:

{
   path: '/ting',
   name: 'Ting',
   component: Ting
}

用这个来获取参数:

this.$route.query.age

4. 通过url

在路由文件的index.js配置

{
        path:'/mydata/:age/:hobby',
        component:Mydata
}

因为我们需要传递agehobby两个参数,现在路由的index.js中配置好。
然后在src/components路径下创建一个Mydata.vue。我们在页面里输出了url传递的的新闻ID和新闻标题。

<template>
    <div>
        <p>我的年龄:{{ $route.params.age}}</p>
        <p>我的爱好:{{ $route.params.hobby}}</p>
    </div>
</template>
<script>
export default {
  name: 'mydata',
  data () {
    return {
    }
  }
}
</script>

在App.vue文件里加入我们的标签。这时候我们可以直接利用url传值了

<router-link to="/mydata/18/write code">
	mymymymy
</router-link>

总结

本篇文章的分享就到这里啦,大家可以关注博主期待后续的文章偶!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值