vue-router路由传递参数

1、通过 标签中的to传参

基本语法:

valueString
PS:上面to前边是带冒号,后边跟的是一个对象形势的字符串

name:在路由配置文件中起的name值。叫做命名路由,下一节会讲到。
params:要传的参数,它是对象形式,在对象里可以传递多个值。
具体实例如下:
(1)在src/components/Home.vue里面导航中添加如下代码:

<router-link :to="{name: 'one', params:{username:'test123'}}">子页面1</router-link>

(2)在src/router/indes.js中添加如下代码,重点是name:

{
    path:'one', // 子页面1
    name: 'one', // 路由名称-命名路由
    component:One
}3)在src/components/One.vue里面接受参数,代码如下:

<h2>{{$route.params.username}}</h2>

2、url中传递参数

(1)在路由中以冒号传递,在src/router/index.js中加入如下代码:

{
    path:'/home/two/:id/:name', // 子页面2
    component:Two
},

(2)接受参数,在src/components/Two.vuez中加入如下代码:

<p>ID{{ $route.params.id}}</p>
<p>名称:{{ $route.params.name}}</p>3)路由跳转,在src/components/Home.vue中加入如下代码:

<router-link to="/home/two/1/张三">子页面2</router-link>

PS:to前没有冒号为字符串路由,必须全部匹配。
(4)如果路由参数需要有特定的规则,就需要加入正则表达式了,示例如下:

{
    path:'/home/two/:id(\\d+)/:name', // 子页面2
    component:Two
}

3、编程式导航-params传递参数

(1)在src/router/index.js页面加入如下代码:

{
    path:'/home/three', // 子页面3
    name: 'three',
    component:Three
}

(2)在src/components/Three.vue页面加入如下代码:

<p>ID{{ $route.params.id}}</p>
<p>名称:{{ $route.params.name}}</p>

(3)在src/components/Home.vue中加入如下代码:

// template
<button @click="toThreePage">页面3-params传参</button>

// script
methods: {
    toThreePage() {
        this.$router.push({name: 'three', params: {id: 1, name: 'zhangsan'}})
    }
}

说明:
A、动态路由使用params传递参数,在this.$router.push() 方法中path不能和params一起使用,否则params将无效。需要用name来指定页面。
B、以上方式参数不会显示到浏览器的地址栏中,如果刷新一次页面,就获取不到参数了,改进方式将第一部中的代码改成如下:

{
    path:'/home/three/:id/:name', // 子页面3
    name: 'three',
    component:Three
}

4、编程式导航-query传递参数

(1)在src/router/index.js页面加入如下代码:

{
    path:'/home/three', // 子页面3
    name: 'three',
    component:Three
}

(2)在src/components/Three.vue页面加入如下代码:

<p>ID{{ $route.query.id}}</p>
<p>名称:{{ $route.query.name}}</p>3)在src/components/Home.vue中加入如下代码:

// template
<button @click="toThreePage">页面3-params传参</button>

// script
methods: {
    toThreePage() {
        this.$router.push({path: '/home/three', query: {id: 1, name: 'zhangsan'}})
    }
}

PS:动态路由使用query传递参数,会显示到浏览器地址栏中,以上链接为
/home/three?id=1&name=zhangsan

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值