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,就是作用域插槽中具名组件的写法

你可能感兴趣的:(vue中slot和v-slot使用)