您现在的位置是:亿华云 > IT科技类资讯

Vue3 学习笔记—插槽使用大全

亿华云2025-10-03 16:03:32【IT科技类资讯】5人已围观

简介在 2.6.0中,vue 为具名插槽和作用于插槽引入了一个新的统一语法:v-slot。它取代了 slot 和 slot-scope 在新版中的应用。本篇文章主要介绍在 vue3 中插槽的使用。一、v-

在 2.6.0中,学习笔vue 为具名插槽和作用于插槽引入了一个新的记插统一语法:v-slot。它取代了 slot 和 slot-scope 在新版中的槽使应用。

本篇文章主要介绍在 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-slot 与 v-bind、v-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 } 

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

很赞哦!(4976)