Slots usage in Vue 3

Slots are a very useful feature in Vue components for passing content from parent components to child components. Vue 3 introduces <script setup>the syntax to make components more concise and readable. In this blog, we'll explore the different ways to use slots in Vue 3, including default slots, named slots, and scoped slots.

default slot

Default slots are the simplest slot usage in Vue components. It allows us to pass content from the parent component to the child component, and use the tag in the child component <slot>to receive this content.

Parent component template:

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

Child component template:

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

Scoped slots

Scoped slots allow parent components to pass data to child components and use directives in child components v-slotto receive that data.

Parent component template:

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

Child component template:

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

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

When using scoped slots, parent components can pass data to child components, and child components use v-slotdirectives to receive data. We can access this data in child components through slotthe attributes of the tag.

chestnut:

parent component:

<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>

Subassembly:

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

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

 

 

To sum it up, slots are used a little differently in Vue 3 than in Vue 2. Using <script setup>the syntax can simplify the writing of components, but when defining the content of the slot, we need to use v-slotor #to specify a named slot or a scoped slot. In the subcomponent, use slotthe tag to receive the slot content, and slotpass the data to the subcomponent through the attribute of the tag.

Guess you like

Origin blog.csdn.net/weixin_60895836/article/details/131987740