1. 程式人生 > >Vue - 插槽(slot)

Vue - 插槽(slot)

插槽,也就是slot,是元件的一塊HTML模板,這塊模板顯示不現實、以及怎樣顯示由父元件來決定。

插槽模板是slot,它是一個空殼子,因為它顯示與隱藏以及最後用什麼樣的html模板顯示由父元件控制。但是插槽顯示的位置由子元件自身決定,slot寫在元件template的哪塊,父元件傳過來的模板將來就顯示在哪塊。這樣就使元件可複用性更高,更加靈活。我們可以隨時通過父元件給子元件加一些需要的東西。

一、插槽內容

插槽內可以是任意內容。首先宣告一個child-component元件,給元件增加一個<slot></slot>插槽。
現在我想在<child-component></child-component>內放置一些內容

<div id="app">
    <child-component>你好</child-component>

</div>
<script>
  Vue.component('child-component',{
        template:`
            <div>
            Hello,World!
            <slot></slot>
            </div>
        `
    })
    let vm 
= new Vue({ el:'#app', data:{ } }) </script>

 

 

二、具名插槽

具名插槽,就是給這個插槽起一個名字
在元件中,我給插槽起個名字,一個名字叫"a",一個名字叫"b",還有一個不起名字。
然後再<child-component></child-component>內,slot屬性對應的內容都會和元件中name一一對應。
而沒有名字的,就是預設插槽!!

<div id="app">
    <child-component>
        <template slot="a">
            漂亮
        
</template> <template slot="b"> 帥氣 </template> <div> 我是預設的插槽 </div> </child-component> </div> <script> Vue.component('child-component',{ template:` <div> <h4>a和b</h4> <slot name="a"></slot> <div style="height:1px;"></div> <slot name="b"></slot> <div style="height:1px;"></div> <slot></slot> </div> ` }) let vm = new Vue({ el:'#app', data:{ } }) </script>

 


三、作用域插槽

在元件上的屬性,可以在元件元素內使用!

<child :lists="nameList">
<template slot-scope="a">
{{a}}
</template>
</child>

<li v-for="list in lists">
<slot :bbbbb="list"></slot>
</li>