前端流行框架Vue3教程:20. 插槽slot(2)

  1. 插槽slot(2)

渲染作用域

插槽内容可以访问到父组件的数据作用域,因为插槽内容本身是在父组件模板中定义的

SlotsTow.vue

vue 复制代码
<script>
export default {
  data() {
    return {};
  }
}
</script>

<template>
  <h3>Slots续集</h3>
  <slot></slot>
</template>

App.vue

vue 复制代码
<script>

import SlotsTow from "@/components/SlotsTow.vue";
export default {
  components: {
    SlotsTow
  },
  data() {
    return {
      message: "插槽内容续集"
    }
  }
}
</script>

<template>
  <SlotsTow>
    <h3>{{ message }}</h3>
  </SlotsTow>
</template>

默认内容

在外部没有提供任何内容的情况下,可以为插槽指定默认内容

vue 复制代码
<template>
  <h3>Slots续集</h3>
  <slot>插槽默认值</slot>
</template>

具名插槽

多个插槽情况下:

SlotsTow.vue

vue 复制代码
<template>
  <h3>Slots续集</h3>
  <slot name="header">插槽默认值</slot>
  <hr>
  <slot name="main">插槽默认值</slot>
</template>

App.vue

vue 复制代码
<template>
  <SlotsTow>
    <template v-slot:header>
      <h3>{{ message }}</h3>
    </template>
    <template v-slot:main>
      <h3>内容</h3>
    </template>

  </SlotsTow>
</template>

v-slot有对应的简写#,因此<template v-slot:header>可以简写为<template #header>。其意思就是"将这部分模板片段传入子组件的header插槽中


相关推荐
Maimai108089 分钟前
React如何用 @microsoft/fetch-event-source 落地 SSE:比原生 EventSource 更灵活的实时推送方案
前端·javascript·react.js·microsoft·前端框架·reactjs·webassembly
candyTong12 分钟前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
kyriewen2 小时前
产品经理把PRD写成“天书”,我用AI半小时重写了一遍,他当场愣住
前端·ai编程·cursor
humcomm2 小时前
元框架的工作原理详解
前端·前端框架
canonical_entropy2 小时前
Attractor Before Harness: AI 大规模开发的方法论
前端·aigc·ai编程
zhangxingchao3 小时前
多 Agent 架构到底怎么选?从 Claude Agent Teams、Cognition/Devin 到工程落地原则
前端·人工智能·后端
IT_陈寒3 小时前
SpringBoot那个自动配置的坑,害我排查到凌晨三点
前端·人工智能·后端
Honor丶Onlyou3 小时前
VS Code 右键菜单修复记录
前端
卡卡军3 小时前
agmd 1.0 重磅升级——Rust 重写,性能起飞
javascript·rust
PILIPALAPENG3 小时前
Python 语法速成指南:前端开发者视角(JS 类比版)
前端·人工智能·python