2023年度鐵人_[Day 23] 父子組件常見操作_part3.(slots插槽)

 

Vue裡面提供了所謂"slots" 插槽的功能,可以在父組件中,將一段 HTML 程式碼傳入到子組件中。
這樣在父組件與子組件合併後,就會將父組件中指定的一段 HTML 程式碼放在子組件中固定的一個位置。
這個位置是在子組件中的,Vue 提供了< slot >元素來實現這個佔位符。

< slot >元素是一個插槽出口,指定了父組件提供的插槽內容將在< slot >元素的指定位置被渲染。

https://ithelp.ithome.com.tw/upload/images/20231002/20107452qDgH2UbtKZ.png
https://vuejs.org/guide/components/slots.html#slot-content-and-outlet

如上圖是插槽出口與插槽內容的關係,渲染時,會將父組件中的插槽內容將子組件中< slot >位置替換掉。

在子組件ChildComponent.vue中,編寫以下程式碼
< div >標記之間留了一個插槽出口的位置,用< slot >先佔個位置。

<template>
    
    <div class="m-5">
        <!-- slots出口 -->
        <slot></slot>
    </div>
</template>

在父組件(在此用App.vue)中使用子組件ChildComponent.vue時,可以指定插槽內容。

<template>
  <main>
    <ChildComponent>
      <!--slot內容可填入html內文-->
      <span class="text-info">slot Content test</span>
    </ChildComponent>
  </main>
</template>

<script setup>
  import ChildComponent from './components/ChildComponent.vue';
</script>

在父組件中,插槽內容是放在子組件
< ChildComponent >開始標記與</ ChildComponent>結束標記之間的內容。
運作之後,插槽內容會替換掉子組件的< slot >程式碼。
子組件中使用< slot >佔個位置,之後在父組件中傳過來一段 HTML 程式碼放在< slot >的位置。

https://ithelp.ithome.com.tw/upload/images/20231002/20107452U3qUjuaV3F.png

如果要讓父組件向子組件傳遞多個插槽內容,這個時候就需要給< slot >指定一個名稱。
子組件中,給< slot >元素指定一個 name 屬性,並賦值為一個名稱。
編修我們的子組件

<template>
    
    <div class="text-info">
        <!-- slots出口 -->
        <slot name="s1"></slot>
    </div>
    <div class="text-success">
        <!-- slots出口 -->
        <slot name="s2"></slot>
    </div>
    
</template>

在兩個< div >元素中使用了< slot >元素,並分別指定了name 屬性和值。
有了 name 屬性,在父組件中,就可以將不同的插槽內容塞到指定的 name 插槽中。

編修父組件如下:

<template>
  <main>
    <ChildComponent>
      <template v-slot:s1>
        <!--slot內容可填入html內文-->
        <span style="color: blue;">slot Content test1</span>
      </template>
      <template v-slot:s2>
        <!--slot內容可填入html內文-->
        <span style="color: green;">slot Content test2</span>
      </template>
    </ChildComponent>
  </main>
</template>

<script setup>
  import ChildComponent from './components/ChildComponent.vue';
</script>

在父元件中,需要使用< template >元素來指定插槽內容,並用 v-slot:指定子組件中
< slot >元素 name 的值,這樣就會將插槽內容和插槽出口一一對應起來。

https://ithelp.ithome.com.tw/upload/images/20231002/20107452eV3IsVCkgK.png







留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題