iT邦幫忙

1

Vue 之溫習 component 的世界 - slot

網頁上難免有些內容,會需要差不多的架構,僅替換部分的內容,簡單來說,我們前面講到的元件拿來重複利用,只是我們要替換掉部分的內容,讓元件可以達到最佳的利用化,這時候就要介紹的 slot 了,他是元件替換部分內容的角色

首先我們先來創建一個元件:

<div id="app">
    <test-component></test-component>
</div>

<script type="text/x-template" id="test-component">
  <nav aria-label="breadcrumb">
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><slot name="test3">Home</slot></li>
      <li class="breadcrumb-item"><a href="#">Library</a></li>
      <li class="breadcrumb-item active" aria-current="page">Data</li>
    </ol>
  </nav>
</script>

<script>
    Vue.component('test-component', {
        template: '#test-component'
    });
</script>

直接在元件內打字是無效的:

如果我們直接在元件內,打上我們自己想要新增的內容,這是無效的,Vue 並不會去把它編譯出來。

<div id="app">
    <test-component>
        <p>Lorem</p>
    </test-component>
</div>

藉由 slot 新增單一內容:

如果我們的內容只有一個,直接在 x-template 的地方,新增 slot 標籤進去,並在元件內所需要的內容即可。

<div id="app">
    <test-component>
        <!-- 打上我們要新增的內容 -->
        <p>Lorem</p>
    </test-component>
</div>

<script type="text/x-template" id="test-component">
  <nav aria-label="breadcrumb">
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="#">Home</a></li>
      <li class="breadcrumb-item"><a href="#">Library</a></li>
      <li class="breadcrumb-item active" aria-current="page">Data</li>
      <!-- 這裡新增 slot 標籤,把內容插進去 -->
      <slot></slot>
    </ol>
  </nav>
</script>

具名的 slot 替換內容:

如果要替換多處元件的內容,這時候就要把替換的內容跟 slot 標籤對應上

<div id="app">
    <test-component>
        <!-- 打上我們要新增的內容,並賦予 slot 屬性,值可以自定義,但需跟 x-template 的 name 屬性相對應 -->
        <li slot="newHome" class="breadcrumb-item"><a href="#">newHome</a></li>
        <li slot="newLibray" class="breadcrumb-item"><a href="#">newLibray</a></li>
    </test-component>
</div>

<script type="text/x-template" id="test-component">
  <nav aria-label="breadcrumb">
    <ol class="breadcrumb">
      <!-- 在對應的位置上,改成 slot 標籤,並賦予 name 屬性,值可以自定義,但需跟元件要替換的內容的 slot 屬性的值一樣-->
      <slot name="newHome" class="breadcrumb-item"><a href="#">Home</a></slot>
      <slot name="newLibray" class="breadcrumb-item"><a href="#">Library</a></slot>
      <li class="breadcrumb-item active" aria-current="page">Data</li>
    </ol>
  </nav>
</script>

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言