vue插槽

我们经常会有封装组件的需求, 组件需要的往往不只有数据, 有时候我们要给一个模块做内容方面的可自定义, 比如我封装了一个黑板, 但是我有时希望上面是字, 又有时希望上面是图画, 这就要用到插槽了

一. 插槽的基本用法

子组件

<template>
  <el-row>
    <slot></slot>
  </el-row>
</template>

父组件

<template>
  <div>
    <!-- 只需要在子组件中写下<slot>标签 就可以在父组件中直接写入想要给子组件slot标签中写入的内容了 -->
    <slot-view>简单插槽内容</slot-view>
  </div>
</template>

缺点是如果子组件中有多个slot插槽标签  父组件写入的值在子组件的插槽中都会展示(此时页面中就会显示两行 ‘简单插槽内容’ 文字)

<template>
  <el-row>
    <slot></slot>
    <slot></slot>
  </el-row>
</template>

 二. 具名插槽

子组件

<template>
  <el-row>
    <slot name="header"></slot>
    <slot name="bottom"></slot>
  </el-row>
</template>

父组件

<template>
  <div>
    <!-- 顾名思义 具名插槽就是给子组件slot插槽加上一个自己的名字  在父组件中通过tamplate包裹 用v-slot或者简写的#来规定给定哪个插槽中填入数据 -->
    <!-- 这样我们一个项目只需要一个公共插槽组件 通过name来规定在哪个模块使用哪个插槽 -->
    <slot-view>
      <template v-slot:header>
        <div>我是header</div>
      </template>
      <template #bottom>
        <div>我是bottom</div>
      </template>
    </slot-view>
  </div>
</template>

三. 动态插槽

<template>
  <div>
    <!-- 动态插槽就是我们在定义要渲染的子组件插槽内容是可以通过动态的命名方式来决定需要渲染哪个插槽的内容 -->
    <slot-view>
      <template #[header]>
        <div>我是header</div>
      </template>
    </slot-view>
  </div>
</template>
const header = ref("header");

四. 作用于插槽

插槽的内容无法访问到子组件的状态,所以父组件如果要获取插槽子组件中的状态  可以通过让子组件通过props往外抛出  父组件通过v-slot="slotProps"来接收

子组件

<template>
  <el-row>
    <slot :text="greetingMessage" :count="1"></slot>
  </el-row>
</template>
<script setup lang="ts">
import { ref } from "vue";
const greetingMessage = ref("王晶测试");
</script>

父组件

<template>
  <div>
    <slot-view v-slot="slotProps">
      <div>{{ slotProps.text }} {{ slotProps.count }}</div>
    </slot-view>
  </div>
</template>

 

posted @ 2023-04-17 17:46  格里兹曼  阅读(24)  评论(0编辑  收藏  举报