Vue-Router路由传递参数方法规整

路由配置带参数

一.使用冒号(:)的形式传递参数 或者说 采用url传参
二.使用 query 方式传递参数
三.使用 params方式传递参数

一.使用冒号(:)的形式传递参数 或者说 采用url传参

在跳转到欢迎页面(/hello)时,带有两个参数:id 和 userName。

routes: [ //配置路由,使用数组形式
  {
	    path: '/',   //链接路径
	    name: 'index',  //路由名称
    	component: index  //映射的组件
  },
  {
    	path: '/hello/:id/:userName',
    	name: 'hello',
    	component: hello
  }]

(1)如果使用 组件跳转的话,可以这么携带参数:

<router-link to="/hello/123/hangge">跳转到 hello</router-link>

(2)如果使用 js 代码跳转的话,可以这么携带参数:

this.$router.push("/hello/123/hangge");

(3) 页面中通过 $route.params.xxx 获取传递过来的数据

<template>
<div>
  <h1>ID:{{ $route.params.id}}</h1>
  <h1>用户名:{{ $route.params.userName}}</h1>
</div>
</template>

二、使用 query 方式传递参数

query 方式类似 get 传参,即通过 URL 传递参数。而路由列表的 path 不需要配置参数:

export default new Router({
  routes: [ //配置路由,使用数组形式
    {
      path: '/',   //链接路径
      name: 'index',  //路由名称
      component: index//映射的组件
    },
    {
      path: '/hello',
      name: 'hello',
      component: hello
    }
  ]
})

2,参数的传递
(1)如果使用 组件跳转的话,可以这么携带参数:

<router-link :to="{path:'/hello', query:{id:123, userName:'hangge'}}">
跳转到 hello
</router-link>

(2)如果使用 js 代码跳转的话,可以这么携带参数:

this.$router.push({`
  path:'/hello',
  query:{
     id:123, 
     userName:'hangge'
   }
});

(3)参数的获取

页面中通过 $route.query.xxx 获取传递过来的数据。

<template>
<div>
<h1>ID:{{ $route.query.id}}</h1>
<h1>用户名:{{ $route.query.userName}}</h1>
</div>
</template>

三、使用 params 方式传递参数

query 方式类似 get 传参,即通过 URL 传递参数。而路由列表的 path 不需要配置参数:

export default new Router({

routes: [ //配置路由,使用数组形式
{
    path: '/',   //链接路径
    name: 'index',  //路由名称
    component: index//映射的组件
},
{
   path: '/hello',
   name: 'hello',
   component: hello
}]
})

2,参数的传递
注意:params 只能用 name 来引入路由,而不能用 path。
(1)如果使用 组件跳转的话,可以这么携带参数:

<router-link :to="{name:'hello', params:{id:123, userName:'hangge'}}">
跳转到 hello
</router-link>

(2)如果使用 js 代码跳转的话,可以这么携带参数:

this.$router.push({
name:'hello',
params:{id:123, userName:'hangge'}
});

(3)参数的获取

页面中通过 $route.params.xxx 获取传递过来的数据。

<template>
<div>
<h1>ID:{{ $route.params.id}}</h1>
<h1>用户名:{{ $route.params.userName}}</h1>
</div>
</template>
发布了135 篇原创文章 · 获赞 41 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/u014651560/article/details/103479175
今日推荐