slot內容分發的使用

一、定義了一個組件custom,該組件本身已經具備template模板了,直接調用<custom></custom>即可渲染模板

<div id="app">
    <custom></custom>
</div>
<script>
    Vue.component('custom',{
        template:`
            <div class="customStyle">
                <p>custom組件內容一</p>
                <p>custom組件內容二</p>
                <p>custom組件內容三</p>
            </div>
        `
    })
    new Vue({
        el:'#app'
    })
</script>

二、匿名插槽
現在,在使用組件custom的同時,想替換這個組件默認已經定義好的模板,就可以使用slot內容分發
用法:
在<custom></custom>內部寫入一些希望展示的html模板,比如
<custom><div>我是自定義的模板</div></custom>,然後,將組件template用<slot></slot>包裹起來,即:

<div id="app">
    <custom><div>我是自定義的模板</div></custom>
</div>
<script>
    Vue.component('custom',{
        template:`
            <div class="customStyle">
                <slot>
                    <p>custom組件內容一</p>
                    <p>custom組件內容二</p>
                    <p>custom組件內容三</p>
                </slot>
            </div>
        `
    })
    new Vue({
        el:'#app'
    })
</script>

那麼,
當在custom標籤內有自定義的模板時,那麼就會替代slot內部的模板內容,渲染到頁面
而當在custom標籤內沒有自定義的模板,那麼就會渲染slot內部的模板內容

這就是匿名插槽,不用設置名稱屬性name,單個插槽可以放置在組件的任意位置,但是就像它的名字一樣,一個組件中只能有一個該類插槽。相對應的,具名插槽就可以有很多個,只要名字(名稱屬性)不同就可以了。
slot內容分發的使用

二、具名插槽
在custom標籤內有自定義的模板,數量很多,想讓custom標籤內某部分的模板渲染到,組件內部對應的位置時,就使用具名插槽了

<div id="app">
    <custom>

        <div slot="one">替換組價內容一</div>
        <div slot="three">替換組價內容三</div>

        <template slot="two">  //當自定義的模板內容很多時,就可以使用template括起來,寫上slot
            <div>替換組價內容二</div>
            <div>替換組價內容二</div>
            <div>替換組價內容二</div>
            <div>替換組價內容二</div>
            <div>替換組價內容二</div>
        </template>

        <div>替換無名的slot</div>  //沒寫slot屬性值時,就默認替換slot沒有name值的那個模板內容

    </custom>
</div>
<script>
    Vue.component('custom',{
        template:`
            <div class="customStyle">

                    <slot name="one><p">custom組件內容一</p></slot>
                    <slot name="two"><p>custom組件內容二</p></slot>
                    <slot name="three"><p>custom組件內容三</p></slot>

                    <slot><p>我是無名的slot</p></slot>

            </div>
        `
    })
    new Vue({
        el:'#app'
    })
</script>

slot內容分發的使用

三、編譯作用域
slot內容分發的使用
<div id="app"> //id爲app所在的區域都屬於父組件
<custom> //這是父組件,所以這個message渲染的是父組件裏的message
{{message}}
</custom>
</div>
<script>
Vue.component('custom',{
data(){
return {
message:'我是子組件的數據'
}
},
template:`
<div class="customStyle">
{{message}} //這是子組件,所以這個message渲染的是子組件裏的message
<h2>我是默認的永遠都顯示的模板內容</h2>
<slot></slot>

        </div>
    `
})
new Vue({
    el:'#app',
    data:{
        message:'我是父組件的數據'
    }
})

</script>



四、總結:匿名插槽:看到自定義組件內容有模板時,直接聯想到可以替換組件定義時template的<slot></slot>裏的內容,如果模板內容沒有slot包裹,則默認全部永遠都顯示(只要調用了這個組件)
具名插槽:看到自定義組件內容內的模板有slot屬性值,則和組件定義時template的<slot></slot>上的name值一一對應
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章