Vue3-22-组件-插槽的使用详解

插槽是干啥的

插槽 就是 组件中的一个 占位符,
这个占位符 可以接收 父组件 传递过来的 html 的模板值,然后进行填充渲染。
就这么简单,插槽就是干这个的。

要说它的优点吧,基本上就是可以使子组件的内容可以被父组件控制,显得更加灵活。

插槽的关键字

slot : 就是定义插槽的关键字。

插槽的几个小分类

插槽从使用的特点上,可以分为以下几个小类:
1、普通插槽 : 没有任何特殊性,最常规的那种;
2、默认值插槽 : 自带默认值的插槽,父组件没有传值时,会自动渲染默认值;
3、具名插槽 : 顾名思义,就是带名字的插槽,在组件中存在多个插槽时较为常用;
4、作用域插槽 : xxxxxx

插槽的使用案例

下面的案例,基本上包含了插槽常见的使用操作。

1、最简单的使用

【子组件】中声明  插槽;
【父组件】中使用组件的时候,直接传入相应的值。

子组件

<template>

    
    <div class="childdiv">
        
        子组件 - msg : {{ msg }}
        <br>
        
        <slot>slot>
   
    div>
    
template>
    
<script setup lang="ts">

    import { ref } from 'vue'

    // 声明一个变量
    const msg = ref('这是子组件的msg变量')
     
script>
    
<style scoped>

    .childdiv{
        width: 300px;
        border: 1px solid green;
    }

style>

父组件

<template>

    <div class="basediv">
      
        父组件msg : {{ msg }}

        <br>
        <br>
        
        <ChildComponent >
            <span style="color: green;">这是父组件给子组件插槽中传递的内容span>
        ChildComponent>
    
    div>
    
template>
    
<script setup lang="ts">

    import { ref } from 'vue'

    // 引入子组件
    import ChildComponent from './ChildComponent.vue'

    // 声明父组件的一个变量
    const msg = ref('这是父组件的msg变量')
    
script>
    
<style scoped>

    .basediv{
        width: 400px;
        height: 200px;
        border: 1px solid red;
    }
style>

运行结果

Vue3-22-组件-插槽的使用详解_第1张图片

2、带默认值的插槽

 标签中填写一些内容,就是它的默认值;
当父组件没有传值时,会渲染默认值;
当父组件传值时,会渲染父组件传递过来的值。

子组件

<template>

    
    <div class="childdiv">
        
        子组件 - msg : {{ msg }}
        <br>
        
        <slot>
            <span style="color: rgb(126, 0, 128);">子组件中插槽的默认值span>
        slot>
   
    div>
    
template>
    
<script setup lang="ts">

    import { ref } from 'vue'

    // 声明一个变量
    const msg = ref('这是子组件的msg变量')
     
script>
    
<style scoped>

    .childdiv{
        width: 300px;
        border: 1px solid green;
    }

style>

父组件

<template>

    <div class="basediv">
      
        父组件msg : {{ msg }}

        <br>
        <br>

        
        <ChildComponent />
        
        <br>

        
        <ChildComponent >
            <span style="color: green;">这是父组件给子组件插槽中传递的内容span>
        ChildComponent>
    
    div>
    
  
template>
    
<script setup lang="ts">

    import { ref } from 'vue'

    // 引入子组件
    import ChildComponent from './ChildComponent.vue'

    // 声明父组件的一个变量
    const msg = ref('这是父组件的msg变量')
 
script>
    
<style scoped>

    .basediv{
        width: 400px;
        height: 200px;
        border: 1px solid red;
    }
style>

运行效果

Vue3-22-组件-插槽的使用详解_第2张图片

3、具名插槽

组件中如果存在多个插槽,那么给插槽起个名字是一个不错的选择;
一方面在组件内容可以很好地对插槽进行区分;
另一方面,在父组件中使用插槽时,也可以指定名称使用插槽,比较明确。
具名插槽的定义格式  : 
具名插槽的使用方式1 : 
具名插槽的使用方式2 : 
【注意点】
	具名插槽 和 默认插槽可以同时存在;
	默认插槽 会被自动命名为 “default”;
	* 父组件在使用子组件的具名插槽时,建议 使用