Vue 2.60 中, 插槽新增的v-slot


注意v-slot只能添加在<template>上(只有一种例外情况),这一点和已经废弃的slotattribute不同。

作用域插槽

自 2.6.0 起有所更新。已废弃的使用slot-scopeattribute 的语法在这里

有时让插槽内容能够访问子组件中才有的数据是很有用的。例如,设想一个带有如下模板的<current-user>组件:

<span>
  <slot>{{ user.lastName }}</slot>
</span>

我们可能想换掉备用内容,用名而非姓来显示。如下:

<current-user>
  {{ user.firstName }}
</current-user>

然而上述代码不会正常工作,因为只有<current-user>组件可以访问到user而我们提供的内容是在父级渲染的。

为了让user在父级的插槽内容中可用,我们可以将user作为<slot>元素的一个 attribute 绑定上去:

<span>
  <slot v-bind:user="user">
    {{ user.lastName }}
  </slot>
</span>

绑定在<slot>元素上的 attribute 被称为插槽 prop。现在在父级作用域中,我们可以使用带值的v-slot来定义我们提供的插槽 prop 的名字:

<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</current-user>

在这个例子中,我们选择将包含所有插槽 prop 的对象命名为slotProps,但你也可以使用任意你喜欢的名字。


文章作者: Assan
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Assan !
评论
  目录