vue插槽的理解和用法

本文深入解析Vue中的插槽概念,包括基本插槽、具名插槽、作用域插槽等,通过实例展示如何在父组件与子组件间传递结构与数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

§1.插槽

理解:
插槽是什么东西,其实就vue提供的一个父组件在使用子组件的时候向子组件中传递结构的方法,子组件中的slot就相当于函数的形参,父组件中传递的结构就是实参,调用的结果就是实参代替了形参的内容。、

实例:

<!--父组件-->
<template >
  <div id="app">
    <SlotDemo>
      <template slot="header">
        <p>{{ header }}</p>
      </template>
      <template slot="body">
        <p>{{ body }}</p>
      </template>
      <template slot="footer" slot-scope="slotProps">
        // 作用域插槽(用于向子组件向父组件传递,再由父组件传回)
        // 相当于在一个插槽的作用域对象上挂载了一个属性ht
        <p>{{ slotProps.ht }}</p>
      </template>
    </SlotDemo>
  </div>
</template>

data () {
    return {
      header:'我是脑袋',
      body:'身体',
      footer:'我是脚',
    }
},

<!--子组件-->
<template>
    <div>
        <slot name="header"></slot>
        <slot name="body"></slot>
        <slot name="footer" :ht="footer"></slot>
    </div>
</template>

1.基本插槽:

<slot></slot>

2.具名插槽:为插槽指定名称。必须一一对应

<!--父组件-->
<template slot="header">
    <p>{{ header }}</p>
</template>
<!--子组件-->
<slot name="header"></slot>

3.插槽的默认内容

<slot name="header">{ error }</slot>
当父组件给子组件传递结构时,子组件会使用默认值

4.编译作用域:父组件模板的所有东西都会在父级作用域内编译;子组件模板的所有东西都会在子级作用域内编译。

5.作用域插槽

<!--父组件-->
<template slot="footer" slot-scope="slotProps">
        // 作用域插槽(用于向子组件向父组件传递,再由父组件传回)
        // 相当于在一个插槽的作用域对象上挂载了一个属性ht
    <p>{{ slotProps.ht }}</p>
</template>
<!--子组件     -->
<slot name="footer" :ht="footer"></slot>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值