Vue-深入浅出插槽slot

作用域

父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。

默认内容

我们可能希望这个 内绝大多数情况下都渲染文本“Submit”。为了将“Submit”作为后备内容,我们可以将它放在 标签内:

<button type="submit">
  <slot>Submit</slot>
</button>

具名插槽

用法

子组件通过向slot里面添加name属性
父组件通过v-slot属性与其对应

具名缩写

跟 v-on 和 v-bind 一样,v-slot 也有缩写,即把参数之前的所有内容 (v-slot:) 替换为字符 #。例如 v-slot:header 可以被重写为 #header:

官网示例

例如对于一个带有如下模板的 组件:

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

一个不带 name 的 出口会带有隐含的名字“default”

<base-layout>
  <template #header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template v-slot:footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

注意 v-slot 只能添加在 上 (只有一种例外情况,就在下面)

作用域插槽

之前我们使用插槽,父级作用域和子级作用域是互不干扰的,但是有时候我们想获取子级作用域的值
在这里我们可以做到,子组件通过v-mode:绑定想传给父组件的值,父组件通过v-slot接受

官网示例

子组件(current-user)
为了让 user 在父级的插槽内容中可用,我们可以将 user 作为 元素的一个 attribute 绑定上去:
切记这里不是prop传值,是slot的语法,可以把slot所在的 组件的user传递上去

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

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

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

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

独占默认插槽的缩写语法

上面所写用到了v-slot,我们在这里探讨一下

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

当然我们也可以简写,因为就一个,可以使用默认

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

注意默认插槽的缩写语法不能和具名插槽混用,因为它会导致作用域不明确

解构插槽 Prop

动态插槽名

v-slot也可以绑定一些动态的值

 <base-layout>
  <template v-slot:[动态的值]>
    ...
  </template>
</base-layout>

已经废弃的语法

Vue官网-插槽-已经废弃的语法

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李和贵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值