Vue3插槽的使用复习

82 阅读1分钟

插槽的概念

在封装组件时,组件中的某些内容需要用户自定义

示例使用

<template>  
    <my-com>  
       <!-- 插槽中的内容 -->
        <h1>TITLE</h1>
    </my-com>  
</template>  


<template>  
    <div>  
    <h1>这是一段内容</h1>  
    
    <!-- 中间的插槽部分-->  
    <slot></slot>  
    
    <h1>这是二段内容</h1>  
    </div>  
</template>  

效果:

image.png

插槽的后备内容

如果在使用组件时 没有为插槽添加内容,那么后备内容会自动填写

<slot>这是后备内容(如果用户没有指定插槽内容)</slot>

声明带有name的插槽的使用

 <!--组件: -->
<template>  
    <header>  
        <slot name="header">标题默认值</slot>  
    </header>  

    <main>  
        <slot name="default">内容默认值</slot>  
    </main>  

    <footer>  
        <slot name="footer">脚注默认值</slot>  
    </footer>  
</template> 


  
<template>  
<my-article>  
    <template v-slot:header>  
    <h1>title</h1>  
    </template>  
  
<template v-slot:default>  
    <p>222</p>  
    <p>333</p>  
    <p>444</p>  
    <p>555</p>  
    </template>  

    <template v-slot:footer>  
    <h5>author</h5>  
    </template>  
    </my-article>  
</template>

如果在组件中未声明名字 那么默认名字为default 即第二段也可以去掉 v-slot:default

带有name的插槽的简写

v-slot: 可以替换成 # 例如: v-slot:header ---- > 写成 #header

<template #header>  
    <h1>title</h1>  
</template>

作用域插槽

在封装组件的过程中,可以给预留的slot插槽绑定props数据。这种slot称作为作用域插槽

组件使用:

<script setup lang="ts">  
import {ref} from "vue";  
  
const information = ref(  
    {  
    information :{  
    phone: 13699999999,  
    address: '中国'  
    }  
    }  
)  
const messagesValue = ref('abc')  

</script>  
  
<template>  
    <h3>这是test组件</h3>  
    <slot :info="information" :msg="messagesValue">默认插槽值</slot>  
</template>  
  

获取值

<my-test>  
<template #default="scope">  
        {{ scope.info }}  
    <br>  
        {{ scope.msg }}  
</template>  
</my-test>

作用域插槽结构prop

结构赋值接收数据

<my-test>  
<template #default="{ info,msg }">  
    <p> {{ info }} </p>  
    <p> {{ msg }} </p>  
</template>  
</my-test>

使用场景代码:

<script setup lang="ts">  
const list = ref([  
    {id: 1, name: '张三', state: true},  
    {id: 2, name: '李四', state: false},  
    {id: 3, name: '赵六', state: false},  
])  
  
</script>  
  
<template>  
  
<table>  
    <thead>  
        <tr>  
            <th>Id</th>  
            <th>Name</th>  
            <th>State</th>  
        </tr>  
    </thead>  
  
<tbody>  
    <tr v-for="item in list" :key="item.id">  
        <slot :user="item"></slot>  
    </tr>  
</tbody>  
  
</table>  
</template>