路由组件传参

在之前的讲解中,我们知道传递参数可以有两种方式。

一种是声明式,即:

<router-link to="/user/1"></router-link>

另一种是编程式,即:

router.push({ name: 'user', params: { id: '1' }})

这两种方式在组件中可以使用 $route.params.id 来接收参数。但是,也可以不通过这种方式,采用 props 的方式将参数直接赋值给组件,将 $route 和组件进行解耦,如示例代码7-9-1所示。

示例代码7-9-1 路由组件传参
const User = {
    props: ['id'],// 代替this.$route.params.id
    template: '<div>User {{ id }}</div>'
}
const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes: [
        { path: '/user/:id', component: User, props: true },
        // 对于包含命名视图的路由,必须分别为每个命名视图添加'props'选项
        {
            path: '/user/:id',
            components: { default: User, sidebar: Sidebar },
            props: { default: true, sidebar: false }
        }
    ]
})

props 被设置为 true 时,$route.params 的内容将会被设置为组件属性,在组件中可以使用 props 接收。

如果 props 是一个对象,它的值会被设置为组件的 props 属性,在组件中可以使用 props 来接收,代码如下:

const User = {
    props: ['id'],// 获取abc
    template: '<div>User {{ id }}</div>'
}
const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes: [
        { path: '/user/:id', component: User, props: { id: 'abc'} },
    ]
})

注意,此时 props 中的 id 会覆盖掉 path 中路径上的 :id,所以这种情况可以理解为给组件的 props 设置静态值。

props 也可以是一个函数,这个函数提供一个 route 参数,这样就可以将参数转换为另一种类型,将静态值与基于路由的值结合,代码如下:

const User = {
    props: ['id'], // 从query中获取id
    template: '<div>User {{id}}</div>'
}
const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes: [
        {
            path: '/user',
            component: User,
            props: (route) => {
                return { id: route.query.id }
            }
        }
    ]
})

当浏览器 URL 是 /user?id=test 时,会将 {id: 'test'} 作为属性传递给 User 组件。