vue中三种不同插槽使用:普通插槽,具名插槽,作用域插槽

本文介绍了Vue.js中的三种插槽用法:普通插槽用于子组件内容替换;具名插槽通过指定名字区分多个插槽;作用域插槽允许父组件访问子组件传递的数据,实现更灵活的内容定制。

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

vue中有三种插槽:普通插槽,具名插槽,作用域插槽

普通插槽:就是放在子组件的一个站位:

父组件代码:

  <div class='father'>
    <div>我是父组件</div>
    <son>
      <div>
        这是普通插槽
      </div>
    </son>
  </div>

子组件代码:需要在子组件添加<slot></slot>进行站位,不然不展示

<template>
  <div class=''>
    <div>我是子组件</div>
    <!-- 普通插槽站位 -->
    <slot></slot>
  </div>
</template>

效果:

 具名插槽:给内容添加名字:

先父组件:slot="header",定义好名字,子组件接收

  <template slot="header">

        <div class="fatherBox1">头部内容</div>

      </template>

<template>
  <div class='father'>
    <div class="fatherBox">我是父组件</div>
    <son>
      <template slot="header">
        <div class="fatherBox1">头部内容</div>
      </template>
      <template slot="footer">
        <div class="fatherBox1">底部内容</div>
      </template>
    </son>
  </div>
</template>

子组件接收数据:name="header",这里的name对应父组件定义的名字

 <slot name="header"></slot>

<template>
  <div class=''>
    <div>我是子组件</div>
    <!-- 具名插槽 -->
    <slot name="header"></slot>
    <slot name="footer"></slot>
  </div>
</template>

效果:

 作用域插槽:

可以拿到子主件传递给父组件的数据,是一个对象数据

父组件:#header="scope"中header对应子组件插槽名字,传递的可以是任意类型,但是scope是一个对象

   <template  #header="scope">
        <div class="fatherBox1">数组:{{scope}}</div>
      </template>

<template>
  <div class='father'>
    <div class="fatherBox">我是父组件</div>
    <son>
      <template  #header="scope">
        <div class="fatherBox1">数组:{{scope}}</div>
      </template>
      <template  #footer="scope">
        <div class="fatherBox1">对象:{{scope}}</div>
      </template>
    </son>
  </div>
</template>

<script>
import son from "./son.vue";
export default {
  components: {
    son,
  },
};

子主件: header定义的名字让父组件接收,:arr='arr'是传递数据给父组件

<slot name="header" :arr='arr'></slot>

<template>
  <div class=''>
    <div>我是子组件</div>
    <!-- 作用域插槽 -->
    <slot name="header" :arr='arr'></slot>
    <slot name="footer" :obj='obj'></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [1, 2, 3, 4, 5],
      obj:{
          name:'貂蟬',
          age:18,
          sex:'女'
      }
    };
  },
};
</script>

效果:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值