什麼時候何地使用 Vue 的做用域插槽

做者:Ashish Lahoti
譯者:前端小智
來源:codingnconcept
點贊再看,微信搜索 大遷世界,B站關注【 前端小智】這個沒有大廠背景,但有着一股向上積極心態人。本文 GitHub https://github.com/qq44924588... 上已經收錄,文章的已分類,也整理了不少個人文檔,和教程資料。**

image.png

Vue插槽是一種將內容從父組件注入子組件的絕佳方法。前端

下面是一個基本的示例,若是咱們不提供父級的任何slot位的內容,剛父級<slot>中的內容就會做爲後備內容。vue

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

而後在咱們的父組件中:git

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

編譯後,咱們的DOM將以下所示。github

<div> Override fallback content </div>

咱們還能夠未來自父級做用域的任何數據包在在 slot 內容中。 所以,若是咱們的組件有一個名爲name的數據字段,咱們能夠像這樣輕鬆地添加它。面試

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

<script>
export default {
   data () {
     return {
       text: 'hello world',
     }
   }
}
</script>

爲何咱們須要做用域插槽

咱們來看另外一個例子,假設咱們有一個ArticleHeader組件,data 中包含了一些文章信息。瀏覽器

// 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>

咱們細看一下 slot 內容,後備內容渲染了 info.title微信

在不更改默認後備內容的狀況下,咱們能夠像這樣輕鬆實現此組件。ide

// ParentComponent.vue
<template>
  <div>
    <article-header />
  </div>
</template>

在瀏覽器中,會顯示 title工具

image.png

雖然咱們能夠經過向槽中添加模板表達式來快速地更改槽中的內容,但若是咱們想從子組件中渲染info.description,會發生什麼呢?spa

咱們想像用下面的這種方式來作:

// Doesn't work!
<template>
  <div>
    <article-header>
        {{ info.description }}
    </article-header>
  </div>
</template>

可是,這樣運行後會報錯 :TypeError: Cannot read property ‘description’ of undefined

這是由於咱們的父組件不知道這個info對象是什麼。

那麼咱們該如何解決呢?

引入做用域插槽

簡而言之,做用域內的插槽容許咱們父組件中的插槽內容訪問僅在子組件中找到的數據。 例如,咱們可使用做用域限定的插槽來授予父組件訪問info的權限。

咱們須要兩個步驟來作到這一點:

  • 使用v-bindslot內容可使用info
  • 在父級做用域中使用v-slot訪問slot屬性

首先,爲了使info對父對象可用,咱們能夠將info對象綁定爲插槽上的一個屬性。這些有界屬性稱爲slot props

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

而後,在咱們的父組件中,咱們可使用<template>v-slot指令來訪問全部的 slot props。

// ParentComponent.vue 
<template>
  <div>
    <child-component>
      <template v-slot="article">
      </template>
    </child-component>
  </div>
</template>

如今,咱們全部的slot props,(在咱們的示例中,僅是 info)將做爲article對象的屬性提供,而且咱們能夠輕鬆地更改咱們的slot以顯示description內容。

// ParentComponent.vue 
<template>
  <div>
    <child-component>
      <template v-slot="article">
        {{ article.info.description }}
      </template>
    </child-component>
  </div>
</template>

最終的效果以下:

image.png

總結

儘管Vue 做用域插槽是一個很是簡單的概念-讓插槽內容能夠訪問子組件數據,這在設計出色的組件方面頗有用處。 經過將數據保留在一個位置並將其綁定到其餘位置,管理不一樣狀態變得更加清晰。

~完,我是刷碗智,我要去刷碗了,骨得白


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

原文:https://learnvue.co/2021/03/w...

交流

文章每週持續更新,能夠微信搜索「 大遷世界 」第一時間閱讀和催更(比博客早一到兩篇喲),本文 GitHub https://github.com/qq449245884/xiaozhi 已經收錄,整理了不少個人文檔,歡迎Star和完善,你們面試能夠參照考點複習,另外關注公衆號,後臺回覆福利,便可看到福利,你懂的。

相關文章
相關標籤/搜索