关于vue中的slot的使用

298 阅读1分钟

在vue组件封装过程中,经常用到slot插槽功能,每次用的时候都是稀里糊涂的,新旧语法傻傻分不清楚,每次开发都翻之前代码,今天抽时间整理了一下,丝滑多了

默认插槽

<!-- 父组件 -->
<navigation-link url="/profile"> 
  Your Profile
</navigation-link>

<!-- 子组件 -->
<a v-bind:href="url" class="nav-link" >
  <slot></slot>
  <!-- 等同于 <slot name="default"></slot> -->
</a>

具名插槽 v-slot:即提供插槽的名字

v-slot 只能添加在 <template> 上。而废弃的slot可用在template上,也可用在普通元素上 例如:

<!-- 新语法 -->
<!-- 用在template上 -->
<template v-slot:header> 
    <h1>Here might be a page title</h1>
</template>


<!-- 废弃语法 -->
<!-- 用在template上 -->
<template slot="header"> 
  <h1>Here might be a page title</h1> 
</template>

<!-- 用在普通元素上 -->
<h1 slot="header">Here might be a page title</h1> 

作用域插槽 v-slot:header="slotProps"(替代废弃的slot-scope)

v-slot:插槽名字="插槽接收的prop集合" 1、新语法 v-slot

<!-- 为了让user在父级的插槽内容中可用,我们可以将user作为<slot>元素的一个attribute 绑定上去 -->
<span> 
   <slot :user="user" :school="school">
     {{ user.lastName }}
   </slot>
</span>

<!-- 绑定在<slot>元素上的 attribute 被称为插槽 prop。现在在父级作用域中,我们可以使用带值的v-slot来定义我们提供的插槽 prop 的名字 -->
<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
    {{ slotProps.school.name }}
  </template>
</current-user>

2、废弃语法 slot-scope

在元素上使用特殊的 slot-scope,可以接收传递给插槽的prop。

这里的 slot-scope 声明了被接收的 prop 对象会作为 slotProps 变量存在于 <template> 作用域中。你可以像命名 JavaScript 函数参数一样随意命名 slotPropsslot-scope attribute 也可以直接用于非 <template> 元素 (包括组件):

<!-- slot-scope用在template上 -->
<current-user>
  <template slot="default" slot-scope="slotProps">
    {{ slotProps.msg }} 
  </template>
</current-user>

<!-- slot-scope也可以直接用于普通元素上 (包括组件): -->
<current-user>
    <span slot-scope="slotProps">
    {{ slotProps.msg }}
    </span> 
</current-user>

<!-- `slot-scope` 的值可以接收任何有效的可以出现在函数定义的参数位置上的 JavaScript 表达式 -->
<current-user>
    <span slot-scope="{ msg }">
    {{ msg }}
    </span> 
</current-user>