vue中slot的使用

1、什么是插槽

<slot></slot>
插槽: 是一个预留的位置,父组件在使用子组件时候在子组件标签中的内容会填充到slot的位置

2、 插槽的分类

2.1 默认插槽

直接写在组件标签中的内容会填充到默认的插槽中

// 父组件 app.vue
<template>
	<p>这是子父组件</p>
	<slotDemo>
		<!-- 直接写在子组件中的内容,会填充到默认的插槽中(没有name shuxing ) -->
	 	<p>填充到默认插槽中<p>
	</slotDemo>
</template>
 // 子组件 slotDemo.vue
 <template>
	<p>这是子组件</p>
	<!-- 插槽:预留的位置,父组件中p标签中的内容自动填充到此位置 -->
	<slot></slot>
</template>

2.2 具名插槽

通过 name 属性给插槽起名字,带有 name 的插槽叫做具名插槽。

// 父组件 app.vue
<template>
	<p>这是子父组件</p>
	<slotDemo>
		<!--父组件通过如下形式将这部分模板片段传入子组件的 header 插槽中-->
	 	<template v-slot:header></template>
	 	<!-- 也可以简写成一下形式-->
	 	<template #footer></template> 
	</slotDemo>
</template>
 // 子组件 slotDemo.vue
 <template>
	<p>这是子组件</p>
	<!-- 插槽:预留的位置,父组件中标签的内容通过name填充到不同的位置 -->
	<header>
		<slot name="header"></slot>
	</header>
	<footer>
		<slot name="footer"></slot>
	</footer>
</template>

3.2 作用域插槽

父组件在使用子组件的时候能获得传过来的数据,子组件在渲染时将一部分数据提供给插槽。
在定义插槽的时候把一些数据传递出去,可以像组件传props 那样向插槽的出口传递(如:item=“info”)

注: 默认插槽和具名插槽在接收子组件传递的插槽props 时有些许不同

3.2.1 默认插槽

// 父组件 app.vue
<template>
	<p>这是子父组件</p>
	<slotDemo>
		<p v-slot="slotProps">{{slotProps.item}}-- {{slotProps.count}}</p>
	</slotDemo>
</template>
 // 子组件 slotDemo.vue
 <template>
	<p>这是子组件</p>
	<header>
		<slot :item="info" :count="1"></slot>
	</header>
</template>

3.2.2 具名插槽

// 父组件 app.vue
<template>
	<p>这是子父组件</p>
	<slotDemo>
		<p v-slot:header="slotProps">{{slotProps.item}}-- {{slotProps.count}}</p>
	</slotDemo>
</template>
 // 子组件 slotDemo.vue
 <template>
	<p>这是子组件</p>
	<header>
		<slot name="header" :item="info" :count="1"></slot>
	</header>
</template>

如果同时使用具名插槽与默认插槽,则需要为默认插槽使用显式的 标签
例如:

<template>
  <MyComponent>
    <!-- 使用显式的默认插槽 -->
    <template #default="{ message }">
      <p>{{ message }}</p>
    </template>

    <template #footer>
      <p>Here's some contact info</p>
    </template>
  </MyComponent>
</template>
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值