vue中slot和v-slot使用

默認slot

<li>
   {{value}}
  <button @click="deleteAction">
    <slot>刪除</slot>
  </button>
</li>
<ul>
  <Item v-for="(item, index) in dataSource" :key="index"
   :value="item" 
   :index="index"
    @delete="handleDelete(index)"
    :deleteFunc="handleDelete"
  >
   <img slot="item" src="https://i.52112.com/icon/jpg/256/20200109/71104/3033821.jpg" width="15"/>
</Item>
</ul>

父組件

<template>
	<SlotComponent>
		<template v-slot:default="props">
			<div v-if="props.type === 1">
				我是類型1
			</div>
			<div v-else-if="props.type === 2">
				我是類型2
			</div>
		</template>
	</SlotComponent>
</template>

在父組件中獲取到子組件傳遞來的type需要使用v-slot來定義子組件傳遞過來的數據集合的名字,例子中名字使用的是props。如果要獲取子組件傳過來的type的話,可以通過props.type獲取。這裏可以優化下,用解構的話寫起來會更方便。

子組件

<template v-slot:default="{type}">
	<div v-if="type === 1">
		我是類型1
	</div>
	<div v-else-if="type === 2">
		我是類型2
	</div>
</template>

v-slot後面跟着的:default是什麼?
這裏的:default表示的是單個插槽,也可以省略,直接寫成v-slot=“props”。不過這個縮寫語法只限於單個插槽的情況,如果是具名插槽的話會報錯。

具名slot及作用域插槽

子組件

<li>
   <slot name="item" :width="30"/>
   <slot name="header" v-bind:headerData="headerData"></slot>
   {{value}}
  <button @click="deleteAction">
    <slot name="delete">刪除</slot>
  </button>
</li>

父組件

<ul>
  <Item v-for="(item, index) in dataSource" :key="index"
   :value="item" 
   :index="index"
    @delete="handleDelete(index)"
    :deleteFunc="handleDelete"
  >
   <template  v-slot:item="{width}">
      <img src="https://i.52112.com/icon/jpg/256/20200109/71104/3033821.jpg" :width="width"/>
    </template>
    <template v-slot:header="{headerData}">
			{{headerData}}
		</template>
    <template  v-slot:delete>
      <img src="https://i.52112.com/icon/jpg/256/20190830/56445/2516260.jpg" width="20"/>
    </template>
</Item>
</ul>

v-slot必須放在template上面,通過內部:width=“width"和v-slot:item=”{width}",外部 定義width,就是作用域插槽中具名組件的寫法

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