Vue slot用法(小結)
之前看官方文檔,由于自己理解的偏差,不知道slot是干嘛的,看到小標題,使用Slot分發(fā)內(nèi)容,就以為 是要往下派發(fā)內(nèi)容。然后就沒有理解插槽的概念。其實說白了,使用slot就是先圈一塊地,將來可能種花種菜,也有可能在這塊地上建房子。然而slot可以以一當十,可以插入很多東西。不知明白否?
由于項目經(jīng)驗有限,這篇我就先跟著官網(wǎng)的知識點走,當然會加入自己的部分項目代碼。
關于slot是這樣說的,
除非子組件模板包含至少一個 <slot> 插口,否則父組件的內(nèi)容將會被丟棄。當子組件模板只有一個沒有屬性的 slot 時,父組件整個內(nèi)容片段將插入到 slot 所在的 DOM 位置,并替換掉 slot 標簽本身。
最初在 <slot> 標簽中的任何內(nèi)容都被視為備用內(nèi)容。備用內(nèi)容在子組件的作用域內(nèi)編譯,并且只有在宿主元素為空,且沒有要插入的內(nèi)容時才顯示備用內(nèi)容。
單個 Slot
在子組件內(nèi)使用特殊的<slot>元素就可以為這個子組件添加一個 slot (插槽),在父組件模板里,插入在子組件標簽內(nèi)的所有內(nèi)容將替代子組件的<slot>標簽及它的內(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)容,我將作為默認出現(xiàn)</p>\
</slot>\
</div>'
});
var app = new Vue({
el: '#app'
})
</script>
</body>
</html>
子組件 child-component 的模板內(nèi)定義一個 <slot> 元素,并且用一個 <p> 作為默認的內(nèi)容,在父組件沒有使用 slot 時,會渲染這段默認的文本;如果寫入了 slot ,那就會替換整個 <slot>.所以上列渲染后的結果為:
<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">標題</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>
子組件內(nèi)聲明了3個 <slot> 元素,其中在<div class="main">內(nèi)的<slot> 沒用使用 name 特性,它將作為默認 slot 出現(xiàn),父組件沒有使用 slot 特性的元素與內(nèi)容都將出現(xiàn)在這里.
如果沒有指定默認的匿名 slot, 父組件內(nèi)多余的內(nèi)容片段都將被拋棄.
上例最終渲染后的結果為:
<div id="app">
<div class="container">
<div class="header">
<h2>標題</h2>
</div>
<div class="main">
<p>正文內(nèi)容</p>
<p>更多的正文內(nèi)容</p>
</div>
<div class="footer">
<div>底部信息</div>
</div>
</div>
</div>
在組合使用組件時,內(nèi)容分發(fā)API至關重要.
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue自定義指令上報Google Analytics事件統(tǒng)計的方法
我們經(jīng)常需要接入統(tǒng)計服務以方便運營,這篇文章主要介紹了Vue自定義指令上報Google Analytics事件統(tǒng)計的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
vue3+Typescript實現(xiàn)路由標簽頁和面包屑功能
在使用 Vue.js 開發(fā)后臺管理系統(tǒng)時,經(jīng)常會遇到需要使用路由標簽頁的場景,這篇文章主要介紹了vue3+Typescript實現(xiàn)路由標簽頁和面包屑,需要的朋友可以參考下2023-05-05

