1. 程式人生 > >組件基礎(插槽slot)—Vue學習筆記

組件基礎(插槽slot)—Vue學習筆記

var str com 分享圖片 mage 個數 結果 turn 是什麽

剛開始我們淡淡提過<slot></slot>現在深入了解一下。

slot可以進行父組件傳值到子組件。

比如:我們將hiboy通過<slot>傳遞到組件中。

<body>
    <div id="app">
        <hello>
            Hi boy
        </hello>
    </div>
</body>
<script>
    Vue.component("hello",{
        data:function(){
            
return { list:[1,2,3,4] } }, template:<p><slot></slot></p> }) var app=new Vue({ el:#app }) </script>

結果:

技術分享圖片

當然這不是今天想要講的。今天我們來分析兩種情況。

一、多個插槽傳遞不同內容

這個時候我們需要設值的關鍵參數有: slot=‘ youngam‘,name=‘young‘ (youngam隨便取的,前後一致即可)

例子:我們想要通過兩個<slot>分別傳遞header和footer,<h3>content</h3>作為主要內容區,具體如下代碼。

<body>
    <div id="app">
        <hello>
            <div>header</div>
            <div>footer</div>
        </hello>
    </div>
</body>
<script>
    Vue.component(
"hello",{ template:`<div> <slot></slot> <h3>content</h3> <slot></slot> </div>` }) var app=new Vue({ el:#app }) </script>

錯誤結果:

技術分享圖片

大家可以發現header和footer被當作一個插值進行了兩次傳遞,這當然不是我們想要的。

解決方法:

通過定義slot的值 <div slot="header">header</div>

組件中<slot name="header"></slot>

這樣在插值時就會找對應的slot進行。

修改後代碼:

<body>
    <div id="app">
        <hello>
            <div slot="header">header</div><!--添加slot的值 -->
            <div slot="footer">footer</div>
        </hello>
    </div>
</body>
<script>
    Vue.component("hello",{
        template:`<div>
                    <slot name="header"></slot>    //與上面值對應(運行時刪除備註)
                    <h3>content</h3>
                    <slot name="footer"></slot>
        </div>`
    })

    var app=new Vue({
        el:#app
    })
</script>

二、作用域插槽(插槽Dom類型由父組件決定)

關鍵代碼:slot-scope=‘變量名‘

<template slot-scope="youngam"></template>

例子:

現在我們的組件中有一個數組,通過v-for遍歷到對應li標簽中並實現顯示。

代碼:

<body>
    <div id="app">
        <hello>
        </hello>
    </div>
</body>
<script>
    Vue.component("hello",{
        data:function(){
            return {
                list:[1,2,3,4]
            }
        },
        template:`<div>
                    <ul>
                        <li v-for=item in list>{{item}}</li>
                    </ul>
                  </div>`
    })

    var app=new Vue({
        el:#app
    })
</script>

結果:

技術分享圖片

好的,正確顯示。

但是,此時的ul和li是固定在組件中的,我們想要通過父組件傳遞標簽實現循環時所顯示的是什麽標簽(此時顯示的是<li></li>)

具體做法:將需要傳遞的標簽外面套一層<template slot-scope="隨便一個變量名"></template>標簽

具體代碼:

<body>
    <div id="app">
        <hello>
            <template  slot-scope="youngam">
                <h3>{{youngam.item}}</h3>
            </template>
        </hello>
    </div>
</body>
<script>
    Vue.component("hello",{
        data:function(){
            return {
                list:[1,2,3,4]
            }
        },
        template:`<div>
                    <ul>
                        <slot v-for=item in list :item=item></slot>
                    </ul>
                  </div>`
    })

    var app=new Vue({
        el:#app
    })
</script>

這裏將slot替換成了h3但數據是組件裏的。通過 變量名.循環單個值 的形式可以獲取到數據。

結果:

技術分享圖片

好了,具體類容還是看官方文檔吧。

就是這樣。

組件基礎(插槽slot)—Vue學習筆記