学习笔记:Vue——插槽

关于Vue插槽,只用过最简单的语法,现在完整地走一遍官方文档说明,并且探索更多用法。


 

 

01.如果组件中没有包含一个<slot>元素,则该组件起始标签和结束标签之间的任何内容都会被抛弃。

02.父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。

03.后备(默认)内容

<button type="submit">
  <slot>Submit</slot>
</button>

04.具名插槽

<slot>元素有一个特殊的特性:name

复制代码
<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>
复制代码

一个不带name的<slot>出口会带有隐含的名字"default"

 

05.作用域插槽

让插槽内容能够访问子组件中才有的数据是很有用的。

绑定在<slot>元素上的特性被称为插槽prop

<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</current-user>

独占默认插槽的缩写语法

<current-user v-slot="slotProps">
  {{ slotProps.user.firstName }}
</current-user>

只要出现多个插槽,请始终为所有的插槽使用完整的基于<template>的语法

复制代码
<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>

  <template v-slot:other="otherSlotProps">
    ...
  </template>
</current-user>
复制代码

 

06.解构插槽Prop

<current-user v-slot="{ user }">
  {{ user.firstName }}
</current-user>
<current-user v-slot="{ user: person }">
  {{ person.firstName }}
</current-user>
<current-user v-slot="{ user = { firstName: 'Guest' } }">
  {{ user.firstName }}
</current-user>

 

07.动态插槽名

<base-layout>
  <template v-slot:[dynamicSlotName]>
    ...
  </template>
</base-layout>

 

08.具名插槽的缩写#

复制代码
<base-layout>
  <template #header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template #footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>
复制代码

 

posted on   独自去流浪  阅读(950)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示