【Vue】插槽

51 阅读1分钟

日常开发组件时,操作是一个常用的功能,插槽有具名插槽和作用域插槽。 以下直接使用2.6以后的语法

具名插槽

比如我们开发一个BaseLayout组件

<div class="container">
  <header>
      <slot name="header"></slot>
  </header>
  <main>
      <slot></slot>
  </main>
  <footer>
      <slot name="footer">
          版权所有,翻版必究
      </slot>
  </footer>
</div>

使用该组件

<BaseLayout>
  <template #header>
    这是头部
  </template>
  <div>
    我是主要内容
  </div>
</BaseLayout>

作用域插槽

我们开发一个Heros组件

<template>
  <ul>
      <li v-for="item in list" :key="item.id">
        <slot :item="item">
          {{item.name}}
        </slot>
      </li>
  </ul>
</template>
<script>
export default {
  props: {
    list: {
      type: Array,
      default: () => []
    }
  }
}
</script>

使用该组件

<Heros :list="list">
  <template v-slot="slotProps">
    {{ slotProps.item.nickName }}
  </template>
</Heros>