[Part 4 ] Vue.js 的精随-元件 Slots

Slots ?

想要传入内容到子层中,slots 是另一种可以选择的方式,在 component 预留空间,父层再放入内容。

节录- Kuro 重新认识 vue.js 中的两句话:

  • slot 特性是保留一个空间,可以从外部传入内容,而子元件本身对 slot 没有控制权
  • 子元件不会知道,也不管 slot 被传了什麽东西

基本用法

以下范例皆取自 When/Why to Use Vue Scoped Slots

子层:

// ChildComponent.vue
<template>
  <div>
     <slot> Fallback Content </slot>
  </div>
</template>

父层:

// ParentComponent.vue
<template>
   <child-component>
      Override fallback content
   </child-component>
</template>

经过编译之後,DOM 的内容如下:

<div> Override fallback content </div>

child-component 标签中的内容Override fallback content 会被置入到 ChildComponent.vue component 中 slot的位置

为什麽需要 ?

再看另一个例子,在 ArticleHeader 元件中,会显示文章的资讯 (例如: 标题或是描述)

// ArticleHeader.vue
<template>
  <div>
    <slot v-bind:info="info"> {{ info.title }} </slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      info: {
        title: 'title',
        description: 'description',
      },
    }
  },
}
</script>
// ParentComponent.vue
<template>
  <div>
    <article-header />
  </div>
</template>

如果在外层也需要显示子层中的 description的话.....

// 错误
<template>
  <div>
    <article-header>
        {{ info.description }}
    </article-header>
  </div>
</template>

父层并没有 info 物件, 会报错!!!!

这时候,就可以使用 slots....


作用域

scoped slots 让外层可以取得内层的资料,有两个步骤:

  1. 透过 v-bindslot 可使用 info
  2. 在父层使用 v-slot 取得 slot 属性
// ArticleHeader.vue - Binding Slot Props
<template>
  <div>
    <slot v-bind:info="info"> {{ info.title }} </slot>
  </div>
</template>

v-bind:info="info" slot prop 将子元件内的状态透过 slot 提供给外层

外层透过 templatev-slot 指令

// ParentComponent.vue - using slot props![/images/emoticon/emoticon02.gif](/images/emoticon/emoticon02.gif)
<template>
  <div>
    <child-component>
      <template v-slot="article">
        {{ article.info.description }}
      </template>
    </child-component>
  </div>
</template>

附上官网图解:
scoped slots

取自 Vue.js- Slots


参考

When/Why to Use Vue Scoped Slots
Summer。桑莫。夏天- Vue.js: Slot

下篇预告

  • 生命周期

每日一句
很高兴认识你,收集中...../images/emoticon/emoticon02.gif


<<:  Day12:SwiftUI-List

>>:  Day12 Redis应用实战-String操作

Day29-TypeScript(TS)的模组(Modules) Part1

今天要来说说TypeScript(TS)的模组(Modules), 模组(Modules)定义在一个...

9. 关於 this 的 5 题练习

这篇只包含我自己不熟悉的题型,建议有看到文章的人自己做做看题目! 题目来自 六角学院 的 观念测验:...

今晚来聊聊铼德2349

晚上在看线图的时候,发现铼德2349有几个观点可以提出来跟大家分享。 在今年1月初时,跌破季线,这时...

[Day21] 网格交易机器人行前准备

首先先更新登入的部分,之後会需要登入凭证,这边的一些变数可以再利用 然後是网格交易策略那边,一些参数...

【Day09】列表 List 与 key

简单的 React 列表范例 const uli = { <li>1</li>...