美文网首页Vue3
Vue3基础之插槽

Vue3基础之插槽

作者: 翟小乙 | 来源:发表于2023-06-07 11:29 被阅读0次

简述

我们已经了解到组件能够接收任意类型的 JavaScript 值作为 props,但组件要如何接收模板内容呢?在某些场景中,我们可能想要为子组件传递一些模板片段,让子组件在它们的组件中渲染这些片段。
由此我们可以使用插槽组件,父组件插入模板内容,子组件显示模板。

插槽

  1. 匿名插槽
  2. 具名插槽
  3. 作用域插槽
  4. 动态插槽

1. 匿名插槽

  • 父组件

插槽内容 <button>23</button>

<template>
 <div>   
    <SonB>
        <button>23</button>
    </SonB> 
 </div>
</template>
  • 子组件

显示插槽内容 <slot></slot> 做出插槽出口,有几个 <slot></slot>显示几个 <button>23</button>

<template>
  <div>
        这是B组件
        <slot></slot>
        <slot></slot>
  </div>
</template>

2. 具名插槽

  • 父组件

插槽内容 <template v-slot:xxx>23</template> v-slot 设置插槽名称

<template>
 <div>   
    <SonB>
        <template v-slot:xxx>23</template>
    </SonB> 
 </div>
</template>
  • 子组件

显示插槽内容 <slot name="xxx"></slot>做出插槽出口,name="xxx" 显示v-slot为xxx的插槽。

<template>
  <div>
        这是B组件
        <slot name="xxx"></slot> 
  </div>
</template>

3. 作用域插槽

  • 父组件

插槽内容 v-slot会把子组件的:data 引入过来

 <template>
 <div>   
    <SonB >
        <template v-slot="sonBdata">
             {{sonBdata.data}}
        </template>
    </SonB>  
 </div>
</template>
  • 子组件

通过:data 传递相当于组件prop属性

<template>
  <div>
        这是B组件 
        <div>
            <div v-for="item in list" :key="item.index">
               <slot :data="item"></slot>
            </div>
        </div> 
  </div>
</template>
<script setup>
   import {reactive} from 'vue'
   const list = reactive([
       {name:'张三',age:18},
       {name:'李四',age:18},
       {name:'赵六',age:18}
   ])
</script>

4. 动态插槽

  • v-slot 使用变量v-slot=[sonBdata]
  • 父组件

插槽内容 v-slot和#[]一样,若是使用动态插槽使用#[变量名称]

<template>
 <div>   
    <SonB > 
        <template #[slotStr]>
             123123123123123
        </template>
    </SonB>  
 </div>
</template>
<script setup>    
    import SonB from './SonB.vue';
    import {ref} from 'vue'
    const  slotStr = ref('xxx')
</script>
  • 子组件

通过声明变量,通过name应用插槽

<template>
  <div>
        这是B组件  
        <slot :name="nn"></slot>
  </div>
</template>
<script setup>
   import {ref} from 'vue'
   const nn = ref('xxx') 
</script>

相关文章

  • (十八)补充-Vue3中插槽的使用

    本章我们将了解到的是vue3中常用插槽的使用; vue3中的插槽是在用的时候和vue2的区别略有不同,常见插槽使用...

  • 18、Vue3 作用域插槽

    作用域插槽:让插槽内容能够访问子组件中,vue2中作用域插槽使用slot-scope,vue3中使用v-slot ...

  • vue3-slot-消息框-模态框

    1.前言 1.使用vue3 的slot插槽时,大部分和vue2-slot插槽[https://www.jiansh...

  • 插槽

    插槽的基础使用,

  • 2020-07-23 一次性讲明白vue插槽slot

    vue插槽slot 一、前言 vue官方文档中在"组件基础"内容中提到组件可以通过插槽分发内容,那插槽是怎么使用的...

  • vue插槽slot

    vue插槽slot 一、前言 vue官方文档中在"组件基础"内容中提到组件可以通过插槽分发内容,那插槽是怎么使用的...

  • Vue3:Slot 插槽

    1、匿名插槽 1.1 什么是插槽 插槽(Slot)是 vue 为组件的封装者提供的能力。允许开发者在封装组件时,把...

  • 四。插槽,Attribute 继承

    插槽 在Vue3中,用template标签包裹要填充的内容,v-slot属性也需定义在template标签上,只有...

  • 【融职培训】Web前端学习 第7章 Vue基础教程7 插槽、DO

    一、插槽 插槽基础 默认的情况下,引入的组件,开始标签和结束标签之间不可以添加内容(如果添加了也会被忽略)。 插槽...

  • 【Vue】组件 - 插槽默认值

    基础知识 【Vue】组件 - 插槽的基本用法 【Vue】组件 - 多个插槽 子组件里,在 里写上默认的内容。 在父...

网友评论

    本文标题:Vue3基础之插槽

    本文链接:https://www.haomeiwen.com/subject/sdegedtx.html