在 Vue 中是使用插槽

屬性傳值

先寫一段簡單的代碼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

  1. p標籤外面會有一層div,這個div是沒法去掉的,有人會想,能不能用template代替,實際上是不能夠的,在這裏模版站位符是不能用的。
  2. 若是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>

具名插槽

若是如今有個需求是,headerfooter是由外部引入的該怎麼弄呢?以下語法

<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結構模版

相關文章
相關標籤/搜索