vue3.0 Composition API 上手初體驗 vue組件的具名插槽 slot 的變化

vue3.0 Composition API 上手初體驗 vue組件的具名插槽 slot 的變化

在我講 vue 3.0 的普通組件的內容裏,我提到了具名插槽發生了變化,我當時不清楚新的如何使用。今天查看了一些資料,終於搞明白了。

搞一個帶具名插槽的子組件

直接擼代碼:

<template>
  <table>
    <tr>
      <th>默認插槽:</th>
      <td><slot /></td>
    </tr>
    <tr>
      <th>具名插槽:</th>
      <td><slot name="footer" /></td>
    </tr>
  </table>
</template>

從代碼中可以看到,我使用了 <slot /> 來調用默認的插槽。同時,也使用了 <slot name="footer" /> 來展示具名插槽

vue 2.0 的具名插槽父組件的調用方法

<template>
  <Child>
    這些文字將顯示在組件默認插槽內
    <template slot="footer">
      這裏的文字會顯示在組件的具名插槽內
    </template>
  </Child>
</template>
<script>
import Child from '@/components/child.vue'
export default {
  components: { Child }
}
</script>

如上,我們可以使用 <template slot="footer"> 往具名插槽裏面填充內容。但是,在 vue 3.0 裏面,這種寫法是不被支持的。

vue 3.0 的具名插槽父組件的調用方法

<template>
  <Child>
    這些文字將顯示在組件默認插槽內
    <template v-slot:footer>
      這裏的文字會顯示在組件的具名插槽內
    </template>
  </Child>
</template>
<script>
import Child from '@/components/child.vue'
export default {
  components: { Child }
}
</script>

好的,我們可以看到,原有的語法已經更換爲了 <template v-slot:footer>,其它的內容沒有變化。在瀏覽器中的效果如下圖所示:

這也是語法糖搞多了之後不可避免的問題。作爲開發人員,我們哪有那麼多時間去翻看這些文檔,查看這些語法糖又怎麼更新了呢?當然,vue 的文檔還是做得很好的。

具名插槽的傳值

在原有的語法裏面,可以通過 slot-scope 來接收子組件的傳值,典型的應用可以參考 element-uiTable 組件,官方演示如下圖所示:

但是在 vue 3.0 中,這個寫法已經被廢棄了,更換爲新的寫法。我們重寫我們的子組件代碼如下:

<template>
  <table>
    <tr>
      <th>默認插槽:</th>
      <td><slot /></td>
    </tr>
    <tr>
      <th>具名插槽:</th>
      <td><slot name="footer" /></td>
    </tr>
    <tr>
      <th>傳參插槽:</th>
      <td><slot name="bottom" :color="color" /></td>
    </tr>
    <tr>
      <th>傳對象參插槽:</th>
      <td><slot name="object" v-bind="{ old, name }" /></td>
    </tr>
  </table>
</template>
<script>
export default {
  setup () {
    return {
      color: 'red',
      old: 34,
      name: 'FungLeo'
    }
  }
}
</script>

然後我們的父組件改成

<template>
  <Child>
    這些文字將顯示在組件默認插槽內
    <template v-slot:footer>
      這裏的文字會顯示在組件的具名插槽內
    </template>
    <template v-slot:bottom="scope">
      文字右邊會有個顏色值 >>> {{scope.color}}
    </template>
    <template v-slot:object="scope">
      文字右邊會有多個數據 >>> 名字:{{scope.name}},年齡:{{scope.old}}
    </template>
  </Child>
</template>
<script>
import Child from '@/components/child.vue'
export default {
  components: { Child }
}
</script>

可以看到,我們的父組件獲取子組件傳值,可以通過 v-slot 的自定義命名值來獲取對象數據。

而子組件給父組件傳值,如果是傳單個值,可以用 :color="color" 這樣的語法來進行傳值。如果要傳多個數據,則可以使用 v-bind 來傳一個對象出去。

剛剛嘗試了一下,v-bind 可以縮寫成 : 也就是說,上面的代碼可以寫成 <slot name="object" :="{ old, name }" /> ,但是我個人不推薦這樣寫,有點懵逼。

不過這種插槽傳值在實際開發中的應用較少,大家只要知道有這種用法就可以了。具體什麼應用場景,只有你自己遇到了實際的需求你纔會知道。

好的,有關 vue 3.0 插槽的部分,我就講完了,相關的代碼,我會推到 github 倉庫中,大家可以下載查看。

本文由 FungLeo 原創,允許轉載,但轉載必須保留首發鏈接。


《vue3.0 Composition API 上手初體驗》 文章目錄地址: https://blog.csdn.net/fungleo/category_10020552.html 我會不定期的補充一些相關內容,歡迎關注訂閱!

文章代碼倉庫 https://github.com/fengcms/vue3-demo 會用 git 的朋友,可以去直接下載我的代碼。當然,給我點個 star 啥的,也不是不可以的哈!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章