Vue 3 中的插槽(Slots)用法

插槽(Slots)是 Vue 组件中一种非常有用的功能,用于在父组件中向子组件传递内容。Vue 3 引入了 <script setup> 语法,使得组件的写法更加简洁和易读。在本篇博客中,我们将探讨在 Vue 3 中使用插槽的不同方式,包括默认插槽、具名插槽以及作用域插槽。

默认插槽

默认插槽是 Vue 组件中最简单的插槽用法。它允许我们在父组件中传递内容到子组件,并在子组件中使用 <slot> 标签来接收这些内容。

父组件模板:

<template>
  <ChildComponent>
    <p>这是通过默认插槽传递的内容</p>
  </ChildComponent>
</template>

子组件模板:

<template>
  <div>
    <slot name="header"></slot>
    <slot name="footer"></slot>
  </div>
</template>

作用域插槽

作用域插槽允许父组件向子组件传递数据,并在子组件中使用 v-slot 指令来接收这些数据。

父组件模板:

<template>
  <ChildComponent>
    <template v-slot="{ message }">
      <p>{
   
   { message }}</p>
    </template>
  </ChildComponent>
</template>

子组件模板:

<template>
  <div>
    <slot :message="data.message"></slot>
  </div>
</template>

<script setup>
const data = {
  message: "这是通过作用域插槽传递的数据",
};
</script>

在使用作用域插槽时,父组件可以向子组件传递数据,子组件使用 v-slot 指令来接收数据。我们可以在子组件中通过 slot 标签的属性来访问这些数据。

栗子:

父组件:

<template>
  <AboutView title="没事">
    <img src="" alt="">
//省略地址
  </AboutView>
  <AboutView title="还行" :listData="games">
    <ul v-for="(game,index) in games" :key="index">
      <li>{
   
   { game }}</li>
    </ul>
  </AboutView>
  <AboutView title="优势" >
    <video src="" controls style="width: 200px;height: 200px;"></video>
  </AboutView>
</template>
<script setup>
import AboutView from './views/AboutView.vue';
const games=["英雄联盟","永劫无间","PUBG"]
</script>

子组件:

<script setup>
import { defineProps } from "vue";

const props = defineProps(['title']);
</script>
<template>    
    <div>
        <!-- 使用props.title来显示标题 -->
        <h2>{
   
   { title }}</h2>
        <!-- 其他组件内容 -->
        <slot></slot>
  </div>
</template>

 

扫描二维码关注公众号,回复: 16458864 查看本文章

总结起来,在 Vue 3 中,插槽的使用方式与 Vue 2 中有一些不同。使用 <script setup> 语法可以简化组件的写法,但在定义插槽内容时,我们需要使用 v-slot# 来指定具名插槽或作用域插槽。而在子组件中,使用 slot 标签来接收插槽内容,并可以通过 slot 标签的属性向子组件传递数据。

猜你喜欢

转载自blog.csdn.net/weixin_60895836/article/details/131987740
今日推荐