vue插槽slot的使用

2021-10-08 03:10:50 字數 1811 閱讀 8466

vue的slot是子元件向父元件提供html自定義模版,具體做法是子元件中定義slot模版,然後在父元件中使用template去填充子元件的slot部分,子元件可以通過在slot上新增屬性給父元件傳遞資料。

主要使用在拓展元件上,比如**元件,讓父元件可以自定義每一行的不同情況下的按鈕,而子元件只需要關心一些通用的功能、布局和樣式,業務邏輯部分在父元件處理,常用於一些vue的ui元件庫。

具體寫法可以參考例子,v-slot:slotname是vue2.6以上的寫法,舊寫法是slot=「slotname」 slot-scope=「data」,在例子中可以看到父元件的template的位置與子元件中填充的位置沒有關係,會固定按照子元件的slot位置進行渲染。

例子如下:父元件傳遞給子元件乙個陣列,然後子元件將每乙個陣列項傳遞歸父元件。

>

>

:list

="list"

>

>

預設slottemplate

>

>

預設slot2template

>

v-slot:title

>

>

具名slotp

>

template

>

v-slot:oprs=""

>

@click

="addcount(item,index)"

>

buttonbutton

>

template

>

cus-table

>

div>

template

>

>

import custable from

"./components/custable.vue"

;export

default

, data:()

=>,,

,]};

},methods:}}

;script

>

>

style

>

子元件custable:

>

>

name

="title"

>

slot

>

>

slot

>

>

class

="list-item"

v-for

="(item,index) in list"

:key

="item.id"

>

class

="item-content"

>

}span

>

name

="oprs"

:item

="item"

:index

="index"

>

slot

>

li>

ol>

div>

template

>

>

export

default}}

;script

>

>

li.list-item:nth-child(odd)

.item-content

style

>

效果圖:

Vue 使用插槽(slot)

當父元件向子元件傳值的時候,有時候,父元件傳的並不是單純的數值 字串,有可能是帶標籤 dom 的資料,那麼如何傳值呢?如果我們像正常父向子傳值那樣操作。content hello,slot slott 子元件 class slott div div template export default s...

Vue插槽slot使用

子元件 child1 此時插槽區域內顯示文案hello 父元件 hello用途 讓內容顯示到元件內的指定位置 子元件 child1 顯示預設的插槽 會顯示v slot為content的內容 parent 預設插槽使用default做引數 哈哈哈 具名插槽使用插槽名做引數 具名插槽 用途 讓內容成為某...

vue使用插槽slot

vue中使用slot插槽 父元件 插槽的使用 父元件 父元件接受子元件的資料 child slot header 我是頭部 template footer 我是底部 template 你好我是底部元件 div slot use 子元件的內容 slotcontainder 我是子元件 div 子元件的...