十二 分分钟学会vue3 插槽 slot

72 阅读1分钟

1. slot的作用和默认使用方式

作用:父组件可以将dom内容,指定插入到,子组件的指定位置

父组件

<template>
  <div class="about">
    <!-- 使用自定义组件 -->
    <CustomComponent>
      <div>
        我是父组件插入进来的数据:
        {{ data }}
      </div>
    </CustomComponent>
  </div>
</template>

<script setup lang="ts">
// 引入自定义组件
import CustomComponent from '@/components/CustomComponent.vue'

import { ref } from 'vue'

const data = ref('我是父组件插入的内容')

</script>

子组件

<template>
  <div class="bb" c="dd">
    我是子组件: 
    <div>
      我在这里接收入组件插入进来的dom: <slot></slot>
    </div>
  </div>
</template>

<script setup>


</script>

<style lang="scss" scoped></style>

12-1.png

2. 具名插槽

具名插槽:可以为插槽自定义名称,同一个组件可以插入多个自定义的具名插槽

v-slot:header 可以简写为 #header

父组件

<template>
  <div class="about">
    <!-- 使用自定义组件 -->
    <CustomComponent>
      <template v-slot:header>
        <div>
          我是父组件插入进来的数据:
          {{ data }}
        </div>
      </template>
    </CustomComponent>
  </div>
</template>

<script setup lang="ts">
// 引入自定义组件
import CustomComponent from '@/components/CustomComponent.vue'

import { ref } from 'vue'

const data = ref('我是父组件插入的内容')

</script>

子组件

<template>
  <div class="bb" c="dd">
    我是子组件: 
    <div>
      我在这里接收入组件插入进来的dom: <slot name="header"></slot>
    </div>
  </div>
</template>

<script setup>


</script>

<style lang="scss" scoped></style>

3. 作用域插槽

父组件可以使用子组件的数据

父组件


<template>
  <div class="about">
    <!-- 使用自定义组件 -->
    <CustomComponent>
      <!-- bbb 用来接收子组件传递过来的数据 -->
      <template v-slot:header="bbb">
        <div>
          我是父组件插入进来的数据:
          {{ data }}
          <div>{{ bbb.count }}</div>
        </div>
      </template>
    </CustomComponent>
  </div>
</template>

<script setup lang="ts">
// 引入自定义组件
import CustomComponent from '@/components/CustomComponent.vue'

import { ref } from 'vue'

const data = ref('我是父组件插入的内容')
</script>

子组件


<template>
  <div class="bb" c="dd">
    我是子组件:
    <div>我在这里接收入组件插入进来的dom: <slot name="header" :count="aaa"></slot></div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const aaa = ref('我是子组件的数据')
</script>

<style lang="scss" scoped></style>

12-2.png