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

在 2.6.0中,vue 为具名插槽和作用于插槽引入了一个新的统一语法:v-slot。它取代了 slot 和 slot-scope 在新版中的应用。本篇文章主要介绍在 vue3 中插槽的使用。
首页 新闻资讯 行业资讯 Vue3 学习笔记—插槽使用大全

[[442721]]

在 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>
  • 1.

  • 2.

  • 3.

  • 4.

  • 5.

  • 6.

  • 7.

  • 8.

  • 9.

 v-slot 的语法,简化 slot、slot-scope 作用域插槽的功能,相比更加强大,代码效率更高。

二、匿名插槽

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

匿名插槽使用:

复制

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

  • 2.

  • 3.

  • 4.

  • 5.

  • 6.

  • 7.

  • 8.

  • 9.

 虽然 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>
  • 1.

  • 2.

  • 3.

  • 4.

  • 5.

  • 6.

  • 7.

  • 8.

  • 9.

  • 10.

  • 11.

  • 12.

  • 13.

  • 14.

  • 15.

  • 16.

  • 17.

  • 18.

  • 19.

具名插槽缩写

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>
  • 1.

  • 2.

  • 3.

  • 4.

  • 5.

  • 6.

  • 7.

  • 8.

  • 9.

  • 10.

  • 11.

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

四、作用域插槽

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

要使子组件上的属性在插槽内容上可用,需要给 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>
  • 1.

  • 2.

  • 3.

  • 4.

  • 5.

  • 6.

  • 7.

  • 8.

  • 9.

  • 10.

  • 11.

  • 12.

  • 13.

  • 14.

  • 15.

  • 16.

五、动态插槽名

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

如:

复制

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

  • 2.

  • 3.

  • 4.

  • 5.

  • 6.

  • 7.

  • 8.

  • 9.

  • 10.

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

 

39    2021-12-29 07:51:21    Vue3 插件 Vue应用