v-slot与废弃的slot,slot-scope的对比与区别

(一)slot

slot插槽,是Vue提供的一种HTML模版,由子组件提供的一种暴露给父组件的可以传入自定义内容的出口。

slot匿名插槽具名插槽作用域插槽 三种。

匿名插槽(一个元素里只能有一个匿名插槽)

// 子组件
<div class="child1">
     <!--匿名插槽-->
      <slot>匿名插槽按钮</slot>
</div>

// 父组件
<child1>
	<div>插入子组件的内容</div>
</child1>

具名插槽(一个元素可以有多个具名插槽)

// 子组件
<div class="child2">
     <slot name="header"></slot>
     <slot name="body"></slot>
     <slot name="footer"></slot>
</div>

// 父组件
<child2>
	 <div slot="header">父组件传递过来的头部内容</div>
     <div slot="body">父组件传递过来的身体内容</div>
     <div slot="footer">父组件传递过来的页脚内容</div>
</child2>

作用域插槽

作用域插槽:能让父组件插槽内容能够访问子组件中才有的数据,绑定在 元素上的 attribute 被称为插槽 prop

// 子组件
<div class="child3">
      <slot name="top" :data="item"></slot>
</div>

// 父组件 slotprop 为子组件传递过来的参数
<child3>
      <div slot="top" slot-scope="slotprop">{
   
   {slotprop.data}}</div>
 </child3>

(二)v-slot

vue2.6及已上 版本,slot 和slot-scope 已经开始 废弃, 有了新的替代: v-slot,v-slot只能用在template 上,和组件标签上。

v-slot的匿名插槽
和 slot 的使用几乎一模一样

// 子组件
<div class="child4">
      <slot></slot>
</div>

// 父组件
<child4 v-slot>
     <div>top</div>
</child4>

v-slot的具名插槽

// 子组件
<div class="child5">
      <slot name="header"></slot>
      <slot name="body"></slot>
      <slot name="footer"></slot>
</div>

// 父组件 具名插槽不缩写
<child5>
    <template v-slot:header>header</template>
    <template v-slot:body>body</template>
    <template v-slot:footer>footer</template>
</child5>

// 父组件 具名插槽缩写
<child>
    <template #header>header</template>
    <template #body>body</template>
    <template #footer>footer</template>
</child>

v-slot的作用域插槽

// 子组件
<div class="child">
	<slot name="parameter" :data="obj"></slot>
</div>

// 父组件 具名插槽不缩写
<child>
	<template v-slot:parameter="obj">{
   
   {obj}}</template>
</child>

// 父组件 具名插槽缩写
<child>
	<template #parameter="obj">{
   
   {obj}}</template>
</child>

猜你喜欢

转载自blog.csdn.net/qq_40893035/article/details/114384490