Vue中插槽的使用

2021-10-04 21:03:14 字數 2116 閱讀 2762

vue插槽常用的分為三種:預設插槽、具名插槽和作用域插槽。

1、預設插槽:

child.vue

<

/slot>

<

/div>

<

/template>father.vue

預設插槽<

/child>

<

/div>

<

/template>

import child from

'./child.vue'

export

default

}<

/script>這時候在子元件裡面放置的內容(可以是文字,也可以是元件)就會生效

2、具名插槽:

當出現了多個插槽時,為了區分不同的插槽,就給每個插槽取乙個名稱。

child.vue

"title"

>

<

/slot>

"content"

>

<

/slot>

"foot"

>

<

/slot>

<

/div>

<

/template>father.vue

/h3>

<

/template>

我是內容<

/div>

<

/template>

我是底部<

/span>

<

/template>

<

/child>

<

/div>

<

/template>

import child from

'./child.vue'

export

default

}<

/script>3、作用域插槽

在插槽中,子元件和父元件都有自己的作用域,只能拿到自己的資料。而作用域插槽作用是為了父元件拿到子元件的資料。

在專案有不同一面中有相同樣式的列表,這時一般會把迴圈出來的列表抽離成乙個元件。

child.vue

for=

"(item, index) in list"

:key=

"index"

>

="left"

>

"image"

:row=

"item"

>

<

/slot>

<

/div>

="right"

>

="name"

>

"name"

:row=

"item"

>

<

/slot>

<

/div>

<

/div>

<

/li>

<

/ul>

<

/div>

<

/template>

export

default}}

<

/script>這裡就把item傳給row

father.vue

"list"

>

<

!--實際接受到的資料格式為:

},所以這裡可以使用結構賦值--

>

"">

"row.head_url" alt=

"">

<

/template>

"">

}<

/template>

<

/child>

<

/div>

<

/template>

import child from

'./child.vue'

export

default

,data()

,,]}

}}<

/script>

Vue中插槽的使用。

寫在前面 vue中插槽的使用讓元件變得更加靈活。使得封裝乙個元件的復用性和api的暴露更加靈活多變。當元件當做標籤使用的時候,在標籤裡面的元素不會顯示,這個時候就需要用到插槽。一 最基本的使用 當元件當做標籤使用的時候,在元件標籤內部的標籤往往不顯示,這個時候就需要用到插槽。寫在元件標籤內部的標籤需...

Vue中插槽的使用

1.兩個元件 元件b h1 div template export default script style 元件a testb div template import testb from components testb export default script style 現在元件a的效果 ...

vue中的插槽的使用

匿名插槽就是可以在父元件中的子元件的標籤中直接新增內容 子元件a 我是a元件中的對話方塊 父元件 在元件外,我們可以往插槽裡填入任何元素,dialog a為元件的名稱 只有子元件中使用了slot才能成功在此標籤中新增內容 按鈕 可以是任何元素 具名插槽就是乙個擁有name屬性的插槽,具名插槽可以在同...