Vue-router的三种传参方式

时间:2023-03-08 22:54:59
Vue-router的三种传参方式

第一种传递参数:name传参

两步完成name传参并显示在模板中;

第一在router/index.js中配置name属性,

routes: [

{

path: '/',

name: 'HelloWorld',

component: HelloWorld

},

]

第二步在src/App.vue接收

  1. {{ $route.name }}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

第二种参数传递方式 通过<router-link>标签中的to传递

首先在src/App.vue中添加

  1. <router-link :to="{name:'hello',params:{userName:'冬天'}}">hello</router-link>

然后在router/index.js中添加name

{

path: '/hello',

name: 'hello',

component: hello,

alias: '/dongtian' //别名

},

最后在hello.vue页面接收

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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

第三种 利用rul传递参数

首先在router/index.js路由中以冒号的形式传递参数,配置路由如下

{

path: '/params/:Id(\\d+)/:title', //只能是数字

component: params

}

然后在params模块利用$route接收参数

  1. <p>Id: {{ $route.params.Id}}</p>
  2. <p>title: {{ $route.params.title}}</p>

最后在src/App.vue模块中的 <router-link>标签中利用rul传值

<router-link to="/params/189/tianshi">params</router-link>