关于vue的slot插槽

插槽内容与出口

代码演示

//子组件 sonComponent  出口
<template>
	//在v-slot标签里面可以放一个默认的数据
	<slot>现在没有内容传进来,"显示我"</slot>
</template>
//父组件 fatherComponent		入口
<sonComponent>
	<button>这里放需要插进子组件的内容</button>
  //...放什么都行
</sonComponent>

渲染作用域

  • 插槽内容可以访问到父组件的作用域,因为插槽内容在父组件模板中
  • 插槽内容不能访问子组件的数据,使用作用域插槽可以访问

具名插槽

代码演示

//子组件 sonComponent  出口
<template>
	 <header>
    <slot name="header">现在没有内容传进来,"显示我"</slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer">现在没有内容传进来,"显示我"</slot>
  </footer>
</template>
//父组件 fatherComponent		入口
<sonComponent>
	<template v-slot:"header">
		<button>这里放需要插进子组件的内容header</button>
  </template>
  <template v-slot:"default">
		<button>这里放需要插进子组件的内容default</button>
  </template>
  <template #footer>
		<button>这里放需要插进子组件的内容default</button>
  </template>
  
</sonComponent>
  • 给slot加一个属性name,这个name用来给各个插槽分配唯一的ID
  • 没有提供属性name的,隐式的被命名为’default’
  • 要为具名插槽传入内容,我们需要使用一个含v-slot指令的元素,并将插槽的名字传给该指令
  • v-slot有对应的简写 # ,因此 v-slot:“header” === #header

动态插槽名

动态参数在v-slot上是有效的

<sonComponent>
  <template v-slot:[dynamicSlotName]>
    ...
  </template>

  <!-- 缩写为 -->
  <template #[dynamicSlotName]>
    ...
  </template>
</sonComponent>

作用域插槽

代码演示

注意,插槽的name是不会穿给父组件的

//子组件 sonComponent  出口
<template>
	<slot :text="message" :count="1"></slot>
	<slot name="slotName" :text="message" :count="1"></slot>
</template>
  • 普通作用域插槽
//父组件 fatherComponent		入口
<sonComponent>
	<template v-slot="slotProps">
		//此时拿到的这个slotProps包括了text和count
		{{slotProps}}
		{{slotProps.message}}
  </template>
</sonComponent>
  • 具名作用域插槽
//父组件 fatherComponent		入口
<sonComponent>
	<template v-slot:slotName="slotProps">
		{{slotProps.message}}{{slotProps.count}}
  </template>
</sonComponent>
  • 简写方式
//父组件 fatherComponent		入口
<sonComponent>
	<template #slotName="slotProps">
		{{slotProps.message}}{{slotProps.count}}
  </template>
</sonComponent>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值