在 Vue 中是使用插槽

屬性傳值

先寫一段簡單的代碼

<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'
})

這種寫法有兩個問題:

  1. p標籤外面會有一層div,這個div是無法去掉的,有人會想,能不能用template代替,其實是不可以的,在這裏模版站位符是不能用的。
  2. 如果content傳遞的內容很多,代碼就會變得很難閱讀。

當我的子組件有一部分內容,是根據父組件傳遞過來的dom進行顯示的話,這時候可以換一種語法。

插槽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>這種語法看起來非常像,用子組我向裏插入內容,所以我們把它叫做插槽。

slot標籤顯示的內容就是父組件向子組件插入進來的內容。

通過插槽可以更方便的向子組件傳遞dom元素,同時子組件只需通過slot來使用就可以了。

slot其他功能

如果子組件裏沒有dom元素,可以讓它顯示默認內容,如下:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章