何時(shí)何地使用 Vue 的作用域插槽
Vue插槽是一種將內(nèi)容從父組件注入子組件的絕佳方法。
下面是一個(gè)基本的示例,如果我們不提供父級(jí)的任何slot位的內(nèi)容,剛父級(jí)<slot>中的內(nèi)容就會(huì)作為后備內(nèi)容。
- // 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>
我們還可以將來(lái)自父級(jí)作用域的任何數(shù)據(jù)包在在 slot 內(nèi)容中。因此,如果我們的組件有一個(gè)名為name的數(shù)據(jù)字段,我們可以像這樣輕松地添加它。
- <template>
- <child-component>
- {{ text }}
- </child-component>
- </template>
- <script>
- export default {
- data () {
- return {
- text: 'hello world',
- }
- }
- }
- </script>
為什么我們需要作用域插槽
我們來(lái)看另一個(gè)例子,假設(shè)我們有一個(gè)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>
我們細(xì)看一下 slot 內(nèi)容,后備內(nèi)容渲染了 info.title。
在不更改默認(rèn)后備內(nèi)容的情況下,我們可以像這樣輕松實(shí)現(xiàn)此組件。
- // ParentComponent.vue
- <template>
- <div>
- <article-header />
- </div>
- </template>
在瀏覽器中,會(huì)顯示 title。
雖然我們可以通過(guò)向槽中添加模板表達(dá)式來(lái)快速地更改槽中的內(nèi)容,但如果我們想從子組件中渲染info.description,會(huì)發(fā)生什么呢?
我們想像用下面的這種方式來(lái)做:
- // Doesn't work!
- <template>
- <div>
- <article-header>
- {{ info.description }}
- </article-header>
- </div>
- </template>
但是,這樣運(yùn)行后會(huì)報(bào)錯(cuò) :TypeError: Cannot read property ‘description’ of undefined。
這是因?yàn)槲覀兊母附M件不知道這個(gè)info對(duì)象是什么。
那么我們?cè)撊绾谓鉀Q呢?
引入作用域插槽
簡(jiǎn)而言之,作用域內(nèi)的插槽允許我們父組件中的插槽內(nèi)容訪問(wèn)僅在子組件中找到的數(shù)據(jù)。 例如,我們可以使用作用域限定的插槽來(lái)授予父組件訪問(wèn)info的權(quán)限。
我們需要兩個(gè)步驟來(lái)做到這一點(diǎn):
- 使用v-bind讓slot內(nèi)容可以使用info
- 在父級(jí)作用域中使用v-slot訪問(wèn)slot屬性
首先,為了使info對(duì)父對(duì)象可用,我們可以將info對(duì)象綁定為插槽上的一個(gè)屬性。這些有界屬性稱為slot props。
- // ArticleHeader.vue
- <template>
- <div>
- <slot v-bind:info="info"> {{ info.title }} </slot>
- </div>
- </template>
然后,在我們的父組件中,我們可以使用<template>和v-slot指令來(lái)訪問(wèn)所有的 slot props。
- // ParentComponent.vue
- <template>
- <div>
- <child-component>
- <template v-slot="article">
- </template>
- </child-component>
- </div>
- </template>
現(xiàn)在,我們所有的slot props,(在我們的示例中,僅是 info)將作為article對(duì)象的屬性提供,并且我們可以輕松地更改我們的slot以顯示description內(nèi)容。
- // ParentComponent.vue
- <template>
- <div>
- <child-component>
- <template v-slot="article">
- {{ article.info.description }}
- </template>
- </child-component>
- </div>
- </template>
最終的效果如下:
總結(jié)
盡管Vue 作用域插槽是一個(gè)非常簡(jiǎn)單的概念-讓插槽內(nèi)容可以訪問(wèn)子組件數(shù)據(jù),這在設(shè)計(jì)出色的組件方面很有用處。通過(guò)將數(shù)據(jù)保留在一個(gè)位置并將其綁定到其他位置,管理不同狀態(tài)變得更加清晰。
~完,我是刷碗智,我要去刷碗了,骨得白
作者:Ashish Lahoti 譯者:前端小智 來(lái)源:codingnconcept
原文:https://learnvue.co/2021/03/when-why-to-use-vue-scoped-slots/