五、路由的params参数
1、第一种字符串写法(源码)
1、Message.vue
<!-- 直接/拼接参数;但是要告诉router后面的是参数位,这个要在下面配置项里改 -->
<router-link :to="`/home/message/details/${m.id}/${m.title}/${m.desc}`">
{{m.title}}
</router-link>
2、router/index.js
// ...
{ // 二级路由
path: 'message',
component: Message,
children: [{
name: 'detail',
path: 'details/:id/:title/:desc', // 配置占位符
component: Details,
}]
}
// ...
3、Details.vue
<template>
<ul>
<!-- 用params传就得用params接 -->
<li>消息标题:{{$route.params.title}}</li>
<li>消息内容:{{$route.params.desc}}</li>
</ul>
</template>
4、Result
2、第二种对象写法(源码)
1、Message.vue
<router-link :to="{
name: 'detail',
params: m // 换成 params 即可
}">
{{m.title}}
</router-link>
router/index.js 和 Details.vue 沿用上面第一种时的更改即可
2、注意点!用 params 必须用 name!
3、总结
-
配置路由,声明接收params参数
{ path:'/home', component:Home, children:[ { path:'news', component:News }, { component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', //使用占位符声明接收params参数 component:Detail } ] } ] }
-
传递参数
<!-- 跳转并携带params参数,to的字符串写法 --> <router-link :to="`/home/message/detail/${id}/&{title}`">跳转</router-link> <!-- 跳转并携带params参数,to的对象写法 --> <router-link :to="{ name:'xiangqing', params:{ id:666, title:'你好' } }" >跳转</router-link>
特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!
-
接收参数:
$route.params.id $route.params.title