先寫一段簡單的代碼html
<div id="root"> <child content="<p>Dell</p>"></child> </div> Vue.component('child', { props: { content:String }, template: `<div> <p>hello</p> <div v-html="this.content"></div> </div>`, }) let vm = new Vue({ el: '#root' })
這種寫法有兩個問題:dom
p
標籤外面會有一層div
,這個div
是沒法去掉的,有人會想,能不能用template
代替,實際上是不能夠的,在這裏模版站位符是不能用的。content
傳遞的內容不少,代碼就會變得很難閱讀。當個人子組件有一部份內容,是根據父組件傳遞過來的dom
進行顯示的話,這時候能夠換一種語法。this
slot
<div id="root"> <child> <p>Dell</p> //這種語法看起來很是像,用子組件,我向裏插入內容 </child> </div> Vue.component('child', { props: { content:String }, template: `<div> <p>hello</p> <slot></slot> //slot 標籤顯示的內容就是父組件向子組件插入進來的內容 </div>`, }) let vm = new Vue({ el: '#root' })
<p>Dell</p>
這種語法看起來很是像,用子組我向裏插入內容,因此咱們把它叫作插槽。code
slot
標籤顯示的內容就是父組件向子組件插入進來的內容。component
經過插槽能夠更方便的向子組件傳遞dom
元素,同時子組件只需經過slot
來使用就能夠了。htm
slot
其餘功能若是子組件裏沒有dom
元素,能夠讓它顯示默認內容,以下:class
<slot>默認內容</slot>
若是如今有個需求是,header
和footer
是由外部引入的該怎麼弄呢?以下語法
<div id="root"> <body-content> <div class="header" slot="header">header</div> <div class="footer" slot="footer">footer</div> </body-content> </div> Vue.component('body-content', { props: { content:String }, template: `<div> <slot name="header"></slot> <div class="content">content</p> <slot name="footer"></slot> </div>`, }) let vm = new Vue({ el: '#root' })
slot
標籤name
屬性對應的是組件中slot
屬性,經過這種寫法,能夠在調用子組件時,一次性傳遞多個區域的dom
結構,在子組件裏經過具名插槽來分別使用不一樣部分的dom
結構模版