插槽

作者: 简单tao的简单 | 来源:发表于2024-01-22 09:52 被阅读0次

    具名插槽

    // 父组件
    
    <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>
    

    相关文章

      网友评论

          本文标题:插槽

          本文链接:https://www.haomeiwen.com/subject/ijsyodtx.html