之前看官方文檔,由于自己理解的偏差,不知道slot是干嘛的,看到小標(biāo)題,使用Slot分發(fā)內(nèi)容,就以為 是要往下派發(fā)內(nèi)容。然后就沒有理解插槽的概念。其實說白了,使用slot就是先圈一塊地,將來可能種花種菜,也有可能在這塊地上建房子。然而slot可以以一當(dāng)十,可以插入很多東西。不知明白否?
由于項目經(jīng)驗有限,這篇我就先跟著官網(wǎng)的知識點走,當(dāng)然會加入自己的部分項目代碼。
關(guān)于slot是這樣說的,
除非子組件模板包含至少一個 <slot> 插口,否則父組件的內(nèi)容將會被丟棄。當(dāng)子組件模板只有一個沒有屬性的 slot 時,父組件整個內(nèi)容片段將插入到 slot 所在的 DOM 位置,并替換掉 slot 標(biāo)簽本身。
最初在 <slot> 標(biāo)簽中的任何內(nèi)容都被視為備用內(nèi)容。備用內(nèi)容在子組件的作用域內(nèi)編譯,并且只有在宿主元素為空,且沒有要插入的內(nèi)容時才顯示備用內(nèi)容。
單個 Slot
在子組件內(nèi)使用特殊的<slot>元素就可以為這個子組件添加一個 slot (插槽),在父組件模板里,插入在子組件標(biāo)簽內(nèi)的所有內(nèi)容將替代子組件的<slot>標(biāo)簽及它的內(nèi)容.示例代碼如下:
<!DOCTYPE html><html><head>  <meta charset="utf-8">  <title>示例</title></head><body>  <div id="app">    <child-component>      <p>分發(fā)的內(nèi)容</p>      <p>更多分發(fā)的內(nèi)容</p>    </child-component>  </div>    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>  <script>    Vue.component('child-component', {      template: '/      <div>/        <slot>/          <p>如果父組件沒用插入內(nèi)容,我將作為默認(rèn)出現(xiàn)</p>/        </slot>/      </div>'    });    var app = new Vue({      el: '#app'    })  </script></body></html>子組件 child-component 的模板內(nèi)定義一個 <slot> 元素,并且用一個 <p> 作為默認(rèn)的內(nèi)容,在父組件沒有使用 slot 時,會渲染這段默認(rèn)的文本;如果寫入了 slot ,那就會替換整個 <slot>.所以上列渲染后的結(jié)果為:
<div id="app"> <div> <p>分發(fā)的內(nèi)容</p> <p>更多分發(fā)的內(nèi)容</p> </div></div>
注意:子組件<slot>內(nèi)的備用內(nèi)容,它的作用域時子組件本身.
具名 Slot
給 <slot> 元素指定一個 name 后可以分發(fā)多個內(nèi)容,具名 Slot 可以與單個 Slot 共存,例如下面的示例:
<!DOCTYPE html><html><head>  <meta charset="utf-8">  <title>示例</title></head><body>  <div id="app">    <child-component>      <h2 slot="header">標(biāo)題</h2>      <p>正文內(nèi)容</p>      <p>更多正文內(nèi)容</p>      <div slot="footer">底部信息</div>    </child-component>  </div>    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>  <script>    Vue.component('child-component', {      template: '/      <div class="component">/        <div class="header">/          <slot name="header"></slot>/        </div>/        <div class="main">/          <slot></slot>/        </div>/        <div class="footer">/          <slot name="footer"></slot>/        </div>/      </div>'    });    var app = new Vue({      el: '#app'    })  </script></body></html>            
新聞熱點
疑難解答
圖片精選