Vue3 插槽使用汇总

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue3 插槽使用汇总脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

一、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 插槽使用内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的Vue3 插槽使用汇总全部内容,希望文章能够帮你解决Vue3 插槽使用汇总所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。