Vue Router(7)

将 props 传递给路由组件

   在你的组件中使用 $route 会与路由紧密耦合,这限制了组件的灵活性,虽然这不一定是件坏事,但我们可以通过props配置来解除这种行为:

 

我们可以将下面的代码

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
const routes = [{ path: '/user/:id', component: User }]

替换成

const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const routes = [{ path: '/user/:id', component: User, props: true }]

 

布尔模式

当 props 设置为 true时,route.params 将被设置为组件的props,这允许你在任何地方使用该组件,使得该组件更容易重用和测试。

 

 

命名视图

对于有命名视图的路由,你必须为每个命名视图定义 props 配置

const routes = [
  {
    path: '/user/:id',
    components: { default: User, sidebar: Sidebar },
    props: { default: true, sidebar: false }
  }
]

 

 对象模式

 

 

函数模式

你也可以创建一个返回props的函数。这允许你将参数转换为其他类型,将静态值与基于路由的值相结合等等。

const routes = [
  {
    path: '/search',
    component: SearchUser,
    props: route => ({ query: route.query.q })
  }
]

 

posted on 2022-02-17 11:12  zhishiyv  阅读(16)  评论(0编辑  收藏  举报

导航