插槽

2024-01-22  本文已影响0人  简单tao的简单

具名插槽

// 父组件

<script setup>
import BaseLayout from './BaseLayout.vue'
</script>

<template>
  <BaseLayout>
    <template #header>
      <h1>Here might be a page title</h1>
    </template>

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

    <template #footer>
      <p>Here's some contact info</p>
    </template>
  </BaseLayout>
</template>
// 子组件

<template>
  <div class="container">
    <header>
      <slot name="header"></slot>
    </header>
    <main>
      <slot></slot>
    </main>
    <footer>
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

<style>
footer {
    border-top: 1px solid #ccc;
    color: #666;
    font-size: 0.8em;
}
</style>

作用域插槽

让插槽内容能够访问子组件中的数据

// 父组件

<script setup>
import MyComponent from './MyComponent.vue'
</script>

<template>
    <MyComponent v-slot="slotProps">
       {{ slotProps.text }} {{ slotProps.count }}
    </MyComponent>
</template>
// 子组件

<script setup>
const greetingMessage = 'hello'
</script>

<template>
   <div>
      <slot :text="greetingMessage" :count="1"></slot>
   </div>
</template>
上一篇 下一篇

猜你喜欢

热点阅读