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


相关推荐
万少9 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站11 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名13 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫14 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊14 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter14 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折14 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_14 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
不会敲代码114 小时前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js
Angelial14 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js