VUE.js學習筆記--簡單理解<slot>標簽

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>
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 組件(Component)是Vue.js最核心的功能,也是整個架構設計最精彩的地方,當然也是最難掌握的。...
    六個周閱讀 5,642評論 0 32
  • 這篇筆記主要包含 Vue 2 不同于 Vue 1 或者特有的內容,還有我對于 Vue 1.0 印象不深的內容。關于...
    云之外閱讀 5,074評論 0 29
  • Vue 實例 屬性和方法 每個 Vue 實例都會代理其 data 對象里所有的屬性:var data = { a:...
    云之外閱讀 2,241評論 0 6
  • 此文基于官方文檔,里面部分例子有改動,加上了一些自己的理解 什么是組件? 組件(Component)是 Vue.j...
    陸志均閱讀 3,860評論 5 14
  • 什么是組件? 組件 (Component) 是 Vue.js 最強大的功能之一。組件可以擴展 HTML 元素,封裝...
    youins閱讀 9,527評論 0 13