vue插槽理解

什麼是插槽

插槽就是子組件提供給父組件的一個佔位符, 使用<slot></slot>表示, 父組件能夠在這個佔位符裏填充任何模板代碼, 好比html 組件等,填充的內容會替換子組件裏的slot標籤
子組件html

<template>
    <div>
    <p>今每天氣</p>
    <slot></slot>
    </div>
</template>

父組件code

<div>
    <p>使用slot分發內容</p>
    <SlotChild>天氣真不錯</SlotChild>
</div>
若是子組件沒有使用插槽,父組件若是須要往子組件中填充模板或者html, 是無法作到的

具名插槽

具名插槽就是給插槽取個名字,一個子組件能夠使用多個插槽, 並且放在不一樣地方,父組件填充內容時, 能夠根據這個名字,將內容填充到對應內容中htm

<template>
    <div>
        <div>
            <h1>我是頁頭</h1>
            <slot name="header"></slot>
        </div>
        <div>
            <h1>我是頁尾</h1>
            <slot name="footer"></slot>
        </div>
    </div>
</template>
<div>
    <SlotChild>
        <template v-slot:header>
            <h1>展現頁頭相關內容</h1>
        </template>
        <template v-slot:footer>
            <h1>展現頁尾相關內容</h1>
        </template>
    </SlotChild>
</div>

默認插槽

默認插槽就是指沒有名字的插槽, 子組件未定義的名字的插槽,父級將會把 未指定插槽的填充的內容填充到默認插槽中。模板

<div>
    <div>
        <h1>我是頁頭</h1>
        <slot name="header"></slot>
    </div>
    <div>
        <h1>我是未定義插槽</h1>
        <slot></slot>
    </div>
    <div>
        <h1>我是頁尾</h1>
        <slot name="footer"></slot>
    </div>
</div>
<div>
    <SlotChild>
        <template v-slot:header>
            <h1>展現頁頭相關內容</h1>
        </template>
        <template>
            <h1>未定義名字插槽</h1>
        </template>
        <template v-slot:footer>
            <h1>展現頁尾相關內容</h1>
        </template>
    </SlotChild>
</div>

注意

1.  父級的填充內容若是指定到子組件的沒有對應名字插槽,那麼該內容不會被填充到默認插槽中。
2.  若是子組件沒有默認插槽,而父級的填充內容指定到默認插槽中,那麼該內容就「不會」填充到子組件的任何一個插槽中。
3.  若是子組件有多個默認插槽,而父組件全部指定到默認插槽的填充內容,將「」 「全都」填充到子組件的每一個默認插槽中。di

相關文章
相關標籤/搜索