何時何地使用 Vue 的作用域插槽
Vue插槽是一種將內容從父組件注入子組件的絕佳方法。
下面是一個基本的示例,如果我們不提供父級的任何slot位的內容,剛父級<slot>中的內容就會作為后備內容。
- // ChildComponent.vue
- <template>
- <div>
- <slot> Fallback Content </slot>
- </div>
- </template>
然后在我們的父組件中:
- // ParentComponent.vue
- <template>
- <child-component>
- Override fallback content
- </child-component>
- </template>
編譯后,我們的DOM將如下所示。
- <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。
在不更改默認后備內容的情況下,我們可以像這樣輕松實現此組件。
- // ParentComponent.vue
- <template>
- <div>
- <article-header />
- </div>
- </template>
在瀏覽器中,會顯示 title。
雖然我們可以通過向槽中添加模板表達式來快速地更改槽中的內容,但如果我們想從子組件中渲染info.description,會發生什么呢?
我們想像用下面的這種方式來做:
- // Doesn't work!
- <template>
- <div>
- <article-header>
- {{ info.description }}
- </article-header>
- </div>
- </template>
但是,這樣運行后會報錯 :TypeError: Cannot read property ‘description’ of undefined。
這是因為我們的父組件不知道這個info對象是什么。
那么我們該如何解決呢?
引入作用域插槽
簡而言之,作用域內的插槽允許我們父組件中的插槽內容訪問僅在子組件中找到的數據。 例如,我們可以使用作用域限定的插槽來授予父組件訪問info的權限。
我們需要兩個步驟來做到這一點:
- 使用v-bind讓slot內容可以使用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>
最終的效果如下:
總結
盡管Vue 作用域插槽是一個非常簡單的概念-讓插槽內容可以訪問子組件數據,這在設計出色的組件方面很有用處。通過將數據保留在一個位置并將其綁定到其他位置,管理不同狀態變得更加清晰。
~完,我是刷碗智,我要去刷碗了,骨得白
作者:Ashish Lahoti 譯者:前端小智 來源:codingnconcept
原文:https://learnvue.co/2021/03/when-why-to-use-vue-scoped-slots/