• vue插槽(slot)详解


    简介:

    元素是一个插槽出口 (slot outlet),标示了父元素提供的插槽内容 (slot content) 将在哪里被渲染。

    一:默认插槽的使用

    例:
    父组件:

      <children>
          <p>欢迎学习</p>
        </children>
    
    • 1
    • 2
    • 3

    子组件

    // children 组件
     <div>
      <slot ></slot>
     </div>
    
    • 1
    • 2
    • 3
    • 4

    浏览器最终渲染结果

    <div>
    <p>欢迎学习插槽用法</p>
    </div>
    
    • 1
    • 2
    • 3

    这就是默认插槽的使用方法,但是大多数情况下,不止一个地方需要填入内容,那么如何知道插入的位置呢,那么 具名插槽也就随之而来。

    二:具名插槽

    什么是具名插槽,顾名思义就是有名子的插槽,这样就能明确什么内容插入到什么地方。下面看看具名插槽的使用方法。
    子组件:

      <div>
       <slot name="tools" ></slot>
        <div class=="entry">
         <slot name="entry"><slot>
        </div>
     </div>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    我们写了两个插槽一个名字叫工具插槽tools,这里面就放一些工具方法。
    还有一个名字叫额外的插槽entry,一些额外的数据就放在这里面,下面看看如何使用

      <children>
       <template #tools>
        <ul>
          <li>复制</li>
          <li>分享</li> 
          <li>退出</li>
        </ul>
       </template>
    
        <template #entry>
          <button>点我有惊喜</button>
       </template>
        </children>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    这样就可以在你想要的位置插入不同的内容了。

    还有一个问题,不知道大家有没有看过ant-desgin一个组件的用法比如表格组件

     <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'name'">{{ text.first }} {{ text.last }}</template>
        </template>
    
    • 1
    • 2
    • 3

    这里面的#bodyCell="{ column, text }" 又是什么呢,bodyCell大家都知道是插槽名,那后面的呢,
    { column, text }是参数

     <slot name="tools" :item="id"></slot>
     const id = 1
    
    • 1
    • 2

    我们用时

      <children>
      <template #tools="{item}">
       <p>{{item}}</p>
      </template>
        </children>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    这样我们就可以取到item的值是1

  • 相关阅读:
    C# Onnx Yolov8 Cls 分类
    电脑一键重装系统发现内存占用率过高怎么办
    img2col 卷积优化讲解
    金蝶云星空企业版v8.0如何通过内网穿透实现异地公网远程访问
    RabbitMQ-03(实战 、RabbitMQ 的六种消息模式)
    非工程师指南: 训练 LLaMA 2 聊天机器人
    全面总结C++类模板使用的基础知识
    【异常错误】WSL2设置为全核cpu和全部内存
    leetcode_27_最小栈
    109. 有序链表转换二叉搜索树 ●●
  • 原文地址:https://blog.csdn.net/qq_44806249/article/details/126441376