欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue插槽簡介和使用示例詳解

 更新時間:2023年03月06日 14:23:18   作者:波波仔86  
插槽就是子組件中的提供給父組件使用的一個占位符,用<slot></slot>?表示,父組件可以在這個占位符中填充任何模板代碼,如?HTML、組件等,填充的內(nèi)容會替換子組件的<slot></slot>標(biāo)簽,這篇文章主要介紹了Vue插槽的理解和使用,需要的朋友可以參考下

對于插槽的概念和使用,這是vue的一個難點,這需要我們靜下心來,慢慢研究。以下是我這兩天通過官網(wǎng)和其他資料的學(xué)習(xí)和使用總結(jié)出來的筆記,如有錯誤或者有不同見解的,歡迎留言,一起學(xué)習(xí)。

什么是插槽

插槽就是子組件中的提供給父組件使用的一個占位符,用<slot></slot> 表示,父組件可以在這個占位符中填充任何模板代碼,如 HTML、組件等,填充的內(nèi)容會替換子組件的<slot></slot>標(biāo)簽。

代碼如下:

1、在子組件中放一個占位符

<template>
    <div>
        <h1>今天天氣狀況:</h1>
        <slot></slot>
    </div>
</template>
<script>
    export default {
        name: 'child'
    }
</script>

2、在父組件中給這個占位符填充內(nèi)容

<template>
    <div>
        <div>使用slot分發(fā)內(nèi)容</div>
        <div>
            <child>
                <div style="margin-top: 30px">多云,最高氣溫34度,最低氣溫28度,微風(fēng)</div>
            </child>
        </div>
    </div>
</template>
<script>
    import child from "./child.vue";
    export default {
        name: 'father',
        components:{
            child
        }
    }
</script>

3、展示效果:

現(xiàn)在來看看,如果插槽中沒有放入插槽,同樣的父組件中在子組件中填充內(nèi)容,會是啥樣的:

<template>
    <div>
        <h1>今天天氣狀況:</h1>
<!--        <slot></slot>-->
    </div>
</template>
<script>
    export default {
        name: 'child'
    }
</script>

總結(jié):如果子組件沒有使用插槽,父組件如果需要往子組件中填充模板或者h(yuǎn)tml, 是沒法做到的

插槽的使用

插槽的最最簡單使用,上面已有例子,這里就不寫了,接下來看看,插槽其他使用場景

插槽使用 - 具名插槽

描述:具名插槽其實就是給插槽取個名字。一個子組件可以放多個插槽,而且可以放在不同的地方,而父組件填充內(nèi)容時,可以根據(jù)這個名字把內(nèi)容填充到對應(yīng)插槽中。代碼如下:

1、子組件的代碼,設(shè)置了兩個插槽(header和footer):

<template>
    <div>
        <div class="header">
            <h1>我是頁頭標(biāo)題</h1>
            <div>
                <slot name="header"></slot>
            </div>
        </div>
        <div class="footer">
            <h1>我是頁尾標(biāo)題</h1>
            <div>
                <slot name="footer"></slot>
            </div>
        </div>
    </div>
</template>
 
<script>
    export default {
        name: "child1"
    }
</script>
 
<style scoped>
 
</style>

2、父組件填充內(nèi)容, 父組件通過 v-slot:[name] 的方式指定到對應(yīng)的插槽中

<template>
<div>
    <div>slot內(nèi)容分發(fā)</div>
    <child1>
        <template slot="header">
            <p>我是頁頭的具體內(nèi)容</p>
        </template>
        <template slot="footer">
            <p>我是頁尾的具體內(nèi)容</p>
        </template>
    </child1>
</div>
</template>
 
<script>
    import child1 from "./child1.vue";
 
    export default {
        name: "father1",
        components: {
            child1
        }
    }
</script>
 
<style scoped>
 
</style>

展示效果

參考文獻(xiàn):

https://www.cnblogs.com/mandy-dyf/p/11528505.html

到此這篇關(guān)于Vue插槽的理解和使用的文章就介紹到這了,更多相關(guān)Vue插槽使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論