Vue3 插槽使用汇总

2022-04-15 0 1,045
目录
  • 一、v-slot 介绍
  • 二、匿名插槽
  • 三、具名插槽
  • 四、作用域插槽
  • 五、动态插槽名

一、v-slot 介绍

v-slot 只能用在 template 或组件上使用,否则就会报错。

v-slot 也是其中一种指令。

使用示例:

//父组件代码 
<child-com> 
 <template v-slot:nameSlot> 
  插槽内容 
 </template> 
</child-com> 
 
//组件模板 
<slot name="nameSlot"></slot> 
v-slot 的语法,简化 slot、slot-scope 作用域插槽的功能,相比更加强大,代码效率更高。

二、匿名插槽

当组件中只有一个插槽的时候,可以不设置 slot name 属性,v-slot 后可以不带参数,但是 v-slot 在没有设置 name 属性的插槽口也会带有隐含的 “default”。

匿名插槽使用:

//组件调用 
<child-com> 
 <template v-slot> 
  插槽内容 
 </template> 
</child-com> 
 
//组件模板 
<slot ></slot> 


虽然 v-slot 没有设置参数,但不能删除掉 ,否则插槽内容无法正常渲染。

三、具名插槽

一个组件中有多个插槽的时候,如果没有设置 v-slot 属性值,会默认把元素插到没有设置 name 属性值的 slot 组件中,为了把对应的元素放到指定的位置,就需要借助 v-slot name 属性,把内容对应起来。

具名插槽使用:

//父组件 
<child-com> 
 <template v-slot:header> 
  头部 
 </template> 
 <template v-slot:body> 
  内容 
 </template> 
 <template v-slot:footer> 
  脚 
 </template> 
</child-com> 
     
//子组件   
<div> 
 <slot name="header"></slot> 
 <slot name="body"></slot> 
 <slot name="footer"></slot> 
</div> 


具名插槽缩写:

v-slotv-bindv-on 指令一样,也存在缩写。可以把 v-slot: 简写为 # 号。

如上述 v-slot:footer 可以简写为 #footer 。

上述的父组件代码可以简化为:

<child-com> 
 <template #header> 
  头部 
 </template> 
 <template #body> 
  内容 
 </template> 
 <template #footer> 
  脚 
 </template> 
</child-com> 


注意:和其他指令一样,只有存在参数时,才可以简写,否则是无效的。

四、作用域插槽

有时让插槽内容能够访问子组件中才有的数据是很有用的。当一个组件被用来渲染一个项目数组时,这是一个常见的情况,我们希望能够自定义每个项目的渲染方式。

要使子组件上的属性在插槽内容上可用,需要给 slot 绑定一个属性。然后在 v-slot 处接收并定义提供插槽 props 名字。

使用示例:

// 
<child-com> 
 <template v-slot:header="slotProps"> 
  插槽内容--{{ slotProps.item }} 序号--{{ slotProps.index }} 
 </template> 
</child-com> 
     
//子组件代码 
<template> 
 <div v-for="(item, index) in arr" :key="index"> 
  <slot :item="item" name="header" :index="index"></slot> 
 </div> 
</template> 
<script setup> 
 const arr = ['1111', '2222', '3333'] 
</script> 


五、动态插槽名

v-slot 指令参数也可以是动态的,用来定义动态插槽名。

如:

<child-com> 
 <template v-slot:[dd()]> 
  动态插槽名 
 </template> 
</child-com> 
 
<script setup> 
const dd = () => { 
  return 'hre' 
} 


此处使用的是函数,也可以直接使用变量。

到此这篇关于Vue3 插槽使用汇总的文章就介绍到这了,更多相关Vue3 插槽使用内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 JavaScript Vue3 插槽使用汇总 https://www.niceym.com/22045.html