vue 插槽 slot

一、匿名插槽(單插槽)

  1. 在父組件中
<Children>
    <div>hello world</div>
    <div>hello world</div>
</Children>
  1. 在子組件中,使用 slot 標(biāo)簽定義插槽位置
    slot 標(biāo)簽內(nèi)的值是插槽無(wú)內(nèi)容時(shí)的默認(rèn)值,當(dāng)插槽有內(nèi)容時(shí)會(huì)被替換掉
<slot>no data</slot>

二、具名插槽(多插槽)

  1. 在父組件中,通過(guò) v-slot 指令指定插槽名稱
    default 為默認(rèn)插槽,在子組件中可以通過(guò) name 指定插槽位置,也可以去掉 name 屬性
<Children>
    <template v-slot:title>
        <h2>具名插槽</h2>
    </template>
    <template v-slot:default>
        <h2>默認(rèn)的具名插槽</h2>
    </template>
</Children>
  1. 在子組件中,設(shè)置插槽的顯示出口
<slot name="title">no data</slot>

<!-- 默認(rèn)插槽的兩種寫(xiě)法 -->
<slot name="default">no data defalut</slot>
<slot>no data defalut</slot>

三、作用域插槽

在父組件的作用域插槽中可以使用插槽出口所在的子組件中的 data 和 methods

  1. 在父組件的作用域插槽中,接收來(lái)自子組件暴露的參數(shù),可以說(shuō) data,也可以是 methods
<template>
    <div>
        <h1>App</h1>
        <Children>
            <!-- 具名插槽 -->
            <template v-slot:title>
                <h2>{{ titleValue }}</h2>
            </template>

            <!-- 作用域插槽 -->
            <template v-slot:titleScope="{ titleScopeValue, changeTitleScopeValue }">
                <h2>{{ titleScopeValue }}</h2>
                <h2 @click="changeTitleScopeValue">{{ titleScopeValue }}</h2>
            </template>
        </Children>
    </div>
</template>

<script>
import Children from '@/components/Children.vue';
export default {
    components: {
        Children,
    },
    data() {
        return {
            titleValue: '具名插槽',
        };
    },
};
</script>
  1. 在子組件中通過(guò) <slot> 給父組件傳遞暴露的 data 和 methods
<template>
    <div>
        <hr />
        <h1>Children</h1>
        <slot name="title">no data</slot>
        <slot name="titleScope" :titleScopeValue="titleScopeValue" :changeTitleScopeValue="changeTitleScopeValue">no scope data</slot>
    </div>
</template>

<script>
export default {
    data() {
        return {
            titleScopeValue: '作用域插槽 data',
        };
    },
    methods: {
        changeTitleScopeValue() {
            this.titleScopeValue = '作用域插槽 methods';
        },
    },
};
</script>

<style lang="scss" scoped></style>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容