slot
官方稱之為”插槽”,我理解就是像是內存插槽的意思,我在子組件里提供這么一個<slot>標簽(相當于主板提供的內存插槽)至于插入什么內容(插幾G的內存)那是父組件需要提供的(由主機配置決定)。舉個栗子:
我們繼續改造一下之前的<li-test>的案例:
<template>
<div>
<input class = 'aaa' v-model.trim="inputValue"/>
<button @click="handleSubmit">提交</button>
<span>{{inputValue}}</span>
<ul>
<li-test
v-for="(item,index) of list"
:key="index"
:content='item'
:index='index'
@delete='handleDelete'
>顯示的是傳遞到子組件中,循環出來的item內容哦</li-test>
</ul>
<!-- 即使 Alt 或 Shift 被一同按下時也會觸發 -->
<button @click.middle ="onClick">A</button>
</div>
</template>
我們改造了一下父組件,在調用子組件<li-test>的模板時在里面增加一段話
執行后,原來新加的話被替換了
執行后可以看出,展示的是模板里的內容,我們在父組件里加的其實已經被替換掉了,但如何讓他顯示呢?這就需要<slot>插槽啦
修改li-test.vue組件:
<template>
<div>
<li class='aaa' @click="handleDelete">{{content}}</li>
<slot></slot>
</div>
</template>
子組件模板中我們加入<slot>組件:
可以看到<slot>標簽直接替換成了我們在父組件增加的話啦
具名slot
上面的例子描述了簡單的slot標簽如何使用,但是有些場景下一個slot可能不能滿足我們的組件需求,對于這樣的情況,<slot> 元素有一個特殊的特性:name。這個特性可以用來定義額外的插槽:官網案例:
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
一個不帶 name 的 <slot> 出口會帶有隱含的名字“default”。
在向具名插槽提供內容的時候,我們可以在一個 <template> 元素上使用 v-slot 指令,并以 v-slot 的參數的形式提供其名稱:
官網案例:
<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>
現在 <template> 元素中的所有內容都將會被傳入相應的插槽。任何沒有被包裹在帶有 v-slot 的 <template> 中的內容都會被視為默認插槽的內容。我們也可以用v-slot:default 來表明默認插槽的內容:
<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<template v-slot:default>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</template>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>
備注:v-slot: 可以縮寫為”#”,但是該縮寫只有在其有參數的時候才可用,以下方法是不可取的:
<!-- 這樣會觸發一個警告 -->
<current-user #="{ user }">
{{ user.firstName }}
</current-user>
如果你希望使用縮寫的話,你必須始終以明確插槽名取而代之:
<current-user #default="{ user }">
{{ user.firstName }}
</current-user>