前端流行框架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插槽中


相关推荐
寅时码3 小时前
React 之死·终章:一个 useRef,把闭包陷阱、依赖数组、漫天 rerender 全送走
前端·react.js·ai编程
不好听6134 小时前
HTML 事件监听机制:从 DOM Level 0 到 React 合成事件
前端·react.js·html
wordbaby4 小时前
为什么刷新页面就 404?聊聊 SPA 路由与 Nginx 的那点事
前端
daols884 小时前
vxe-table 渲染器教程一:实现金额输入控件
javascript·vue.js·vxe-table
不好听6134 小时前
React 核心概念:JSX、组件与数据驱动
前端·react.js
触底反弹4 小时前
🔥 React 零基础入门(中):500 行屎山代码到组件化的蜕变
前端·javascript·react.js
不好听6134 小时前
React vs Vue:两大前端框架技术选型深度对比
前端·vue.js·react.js
GuWenyue4 小时前
Cursor黑盒拆解!1套LangChain.js手写Mini编程Agent,自动生成React项目,效率提升60%
前端·数据库·人工智能
GuWenyue4 小时前
传统Agent工具两大痛点!300行代码落地MCP跨语言工具,彻底解耦LLM与工具
前端·人工智能·算法
小林ixn5 小时前
从 onclick 到 React 合成事件,再到完整应用逻辑:一次前端架构的深度剖析
前端·react.js·前端框架