Vue學習(5)-插槽slot

插槽就是子組件預留給父組件放置內容的空間,如果沒有插槽,那么我們在父組件中使用子組件時,往子組件里添加內容是無效的。
父組件:

<template>
  <div style="text-align: center">
    <todo-item>
      <!-- 子組件標簽里的內容將不會顯示 -->
      <span>這里是父組件DOM</span>
    </todo-item>
  </div>
</template>

那么有什么辦法可以讓子組件標簽像div一樣可以在里面放置內容嗎?當然是有的,就是 我們要介紹的插槽slot。

slot

如果我們在子組件中添加插槽,那么放入子組件標簽中的內容就會被加載到slot中。
子組件:

<template>
  <div style="text-align: center" class='child'>
    <h3>這是子組件</h3>
    <!-- 像這樣添加slot標簽即可 -->
   <slot></slot>
  </div>
</template>

這樣父組件中添加的內容將會替換掉slot,相當于
子組件:

<div style="text-align: center" class='child'>
    <h3>這是子組件</h3>
    <!-- slot標簽會被替換掉 -->
    <span>這里是父組件DOM</span>
</div>

每一個子組件都應該有一個像這樣不帶名字的插槽,稱為單個插槽
同時我們也可以增加一些帶有名字的插槽,控制DOM內容的不同位置,帶有name屬性的插槽稱為具名插槽
子組件

<template>
  <div style="text-align: center" class='child'>
    <slot name="top"></slot>
    <h3>這是子組件</h3>
    <slot></slot>
    <hr style="margin-top: 20px">
    <slot name="down"></slot>
  </div>
</template>

父組件中要添加slot屬性:

<template>
  <div style="text-align: center">
    <todo-item>
      <span class="father-dom">這里是父組件DOM</span>
      <span slot="down">這是底部</span>
      <span slot="top">這是頂部</span>
    </todo-item>
  </div>
</template>

不管父組件中增加的DOM先后順序如何,具名插槽總是對應到同名的子組件位置處,剩下的對應到單個插槽處。如果在父組件中給了slot屬性,但是子組件中并沒有該插槽,那么那個標簽將不會顯示。

slot-scope

這個屬性是給父組件中插入在子組件標簽中的DOM使用的,可以獲取插槽上的屬性值。
父組件

<template>
  <div style="text-align: center">
    <todo-item :message="message">
      <template slot-scope="scope">
        <span>{{scope}}</span><br>
        <span>{{scope.data}}</span>
      </template>
    </todo-item>
  </div>
</template>

子組件:

<template>
  <div style="text-align: center" class='child'>
    <h3>這是子組件</h3>
    <slot :data="message"></slot>
  </div>
</template>

父組件中slot-scope綁定的scope對應的數據就是子組件中slot上的data。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 以下內容是我在學習和研究Vue時,對Vue的特性、重點和注意事項的提取、精練和總結,可以做為Vue特性的字典; 1...
    科研者閱讀 14,142評論 3 24
  • 此文基于官方文檔,里面部分例子有改動,加上了一些自己的理解 什么是組件? 組件(Component)是 Vue.j...
    陸志均閱讀 3,866評論 5 14
  • 這篇筆記主要包含 Vue 2 不同于 Vue 1 或者特有的內容,還有我對于 Vue 1.0 印象不深的內容。關于...
    云之外閱讀 5,079評論 0 29
  • 這句話,絕對是一句大實話 2016年,會開始瘋狂的變現,你的朋友圈也好,還有你的微信群里都會不斷有和耳朵產品推送的...
    劉鵬發燒友閱讀 241評論 0 0
  • 初號=42磅 小初=36磅 一號=26磅 小一=24磅 二號=22磅 小二=18磅 三號=16磅 小三=15磅 四...
    WesleyWang閱讀 2,734評論 0 1