很多时候,我们需要将给定匹配模式的路由映射到同一个组件。例如,我们可能有一个 News 组件,它应该对不同的新闻详情进行渲染,但新闻 ID 不同。这个时候,我们可以在路径中使用一个动态字段来实现。
const routes = [
// 动态字段以冒号开始
{ path: '/news/:id', component: News },
]
此时,像 /news/1 和 /news/2 这样的 URL 都会映射到同一个路由。这个时候我们在 News 组件中会使用 this.$route.params.id 方式获取新闻id。
const News = {
template: '<div>新闻id为:{{ $route.params.id }}</div>'
}
然而,在组件中使用 $route 会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的 URL 上使用,限制了其灵活性。此时,我们可以通过使用props 配置将组件和路由解耦
我们可以把代码替换为:
const News = { // 请确保添加一个与路由参数完全相同的 prop 名
props: ['id'],
template: '<div>新闻id为:{{ id }}</div>'}
const routes = [{ path: '/news/:id', component: News, props: true }]
注意:对于有命名视图的路由,你必须为每个命名视图定义 **props** 配置:
const routes = [
{
path: '/news/:id', components: { default: News, sidebar: Sidebar }, props: { default: true, sidebar: false }
}
]
props 配置有布尔、对象、函数三种配置模式,上面演示的为布尔模式。
对象模式:
{ path:'/news/:id', component:News, props:{id:true}}
函数模式:
{
path:'/news/:id',
component:News,
props:route => ({ id: route.params.id })}