如何使用 Vue 命名插槽建立多個模板插槽?

做者:Matt Maribojoc
譯者:前端小智
來源:stackabuse

有夢想,有乾貨,微信搜索 【大遷世界】 關注這個在凌晨還在刷碗的刷碗智。前端

本文 GitHub https://github.com/qq449245884/xiaozhi 已收錄,有一線大廠面試完整考點、資料以及個人系列文章。vue

Vue 插槽容許將父組件中的內容注入到子組件中。git

這是最基本的示例,若是咱們不提供父級的任何slot 內容,則咱們將<slot>放在其中的任何內容都會做爲後備內容。github

// ChildComponent.vue
<template>
  <div>
     <slot> 後備內容 </slot>
  </div>
</template>

你組件代碼:面試

// ParentComponent.vue
<template>
   <child-component>
      替換 slot 的默認內容
   </child-component>
</template>

編譯後,咱們的 DOM 將以下所示微信

<div> 替換 slot 的默認內容 </div>

咱們還能夠將父組做用域內的任何數據寫在 slot 區域中。 例如,父組件有一個名爲title的數據字段,咱們可使用如下代碼將其注入到子組件中:工具

// ParentComponent.vue

<template>
   <child-component>
      {{ title }} 
   </child-component>
</template>

<script>
export default {
   data () {
     return {
       title: '這會傳遞給子組件',
     }
   }
}
</script>

爲何咱們須要命名插槽

在Vue中使用命名插槽有兩個步驟:spa

  1. 使用name屬性從子組件中命名 slot
  2. 使用v-slot指令從父組件向這些命名插槽提供內容

默認狀況下,不給插槽顯式的name屬性時,它有默認名字是defaultdebug

爲了給咱們的 slot 起個名字,<slot>元素具備一個特殊的name屬性,可讓咱們在多個插槽之間進行區分。設計

在下面的 Article.vue 中,咱們命名三個 slot

// Article.vue - Child Component
<template>
  <div>
    <slot name="title"> 默認 title </slot>
    <slot name="content"> 默認 content </slot>
    <slot name="comments"> 默認 comments</slot>
  </div>
</template>

而後,在父組件中,咱們能夠在<template>元素上使用v-slot指令指定咱們想要注入內容的slot

// ParentComponent.vue
<template>
  <div>
    <child-component>
      <template> 個人 Title </template>
      <template> 個人 Content </template>
      <template> 個人 Comments </template>
    </child-component>
  </div>
</template>

由於這是沒有指定 slot 的名稱,因此顯示的是 slot 默認的內容。

image.png

要解決這個問題,可使用v-slot,指定的名稱要確保名稱與咱們在子組件中聲明的名稱徹底匹配。

<template>
  <div>
    <child-component>
      <template v-slot:title> 個人 title </template>
      <template v-slot:content> 個人 content </template>
      <template v-slot:comments> 個人 comments </template>
    </child-component>
  </div>
</template>

再次運行:

image.png

使用 Vue 命名插槽有什麼意義

命名槽讓咱們可使用多個槽,可是爲何這對咱們Vue開發人員有用呢。

簡而言之,它使咱們能夠更好地組織開發代碼,還能夠編寫更具擴展性的代碼。

就我的而言,我認爲最重要的是,它容許咱們在代碼上使用插槽,從而使樣式設計變得更加容易。 在咱們的示例中,Article.vue子組件只有三個插槽,可是在實際應用中,這些插槽看起來更像這樣,以便咱們的組件能夠向每一個部分添加CSS樣式。

<template>
  <div>
    <div class="title">
      <h1>
        <slot name="title"> 默認 Title </slot>
      </h1>
    </div>
    <div class="content">
      <p>
        <slot name="content"> 默認  Content </slot>
      </p>
    </div>
    <div class="comments">
      <slot name="comments"> 默認  Comments </slot>
    </div>
  </div>
</template>

在此示例中,更容易理解爲何咱們須要多個 slot。 因爲咱們注入的內容是經過不一樣的<div><p>和DOM元素彼此分隔的。 沒法在一個slot中傳遞全部這些信息。

image.png

若是檢查DOM,能夠看到使用v-slot的模板將內容正確地插入到正確的位置。

image.png

~完,我是刷碗智,去刷碗了,下期見!


代碼部署後可能存在的BUG無法實時知道,過後爲了解決這些BUG,花了大量的時間進行log 調試,這邊順便給你們推薦一個好用的BUG監控工具 Fundebug

原文:
https://learn.co/2021/04/usin...

交流

有夢想,有乾貨,微信搜索 【大遷世界】 關注這個在凌晨還在刷碗的刷碗智。

本文 GitHub https://github.com/qq44924588... 已收錄,有一線大廠面試完整考點、資料以及個人系列文章。

相關文章
相關標籤/搜索