Vue3种常用插槽的使用

插槽总结 :

  • 插槽的作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件 。
  • 分类:默认插槽、具名插槽、作用域插槽

1、默认插槽

父组件中:

        <Category>
           <div>html结构1</div>
        </Category>


子组件中:

        <template>
            <div>
               <!-- 定义插槽 -->
               <slot>插槽默认内容...</slot>
            </div>
        </template>


 

2、具名插槽

适用场景:父子组件通信(一般传递的是结构)

子组件:

<template>
  <div>
    <slot name="header"></slot>
    <slot name="footer"></slot>
  </div>
</template>

父组件:

<template>
  <div>
    <!-- -->
    <Son>
      <template slot="header">
        <div>html结构1</div>
      </template>
      <template slot="footer">
        <div>html结构2</div>
      </template>
    </Son>
  </div>
</template>

 

3、作用域插槽

数据在子组件的自身,但组件的使用者(父组件)根据子组件中的数据生成对应的自己的DIY结构。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)

适用场景:父子组件通信(一般父组件向子组件传递结构)

子组件:

<template>
  <div>
    <slot :games="games"></slot>
  </div>
</template>

<script>
export default {
  name: "Son",
  props: ["title"],
  data() {
    return {
      games: ["肯德基", "德克士", "麦当劳", "华莱士"],
    };
  },

  mounted() {},
};
</script>

父组件:

<template>
  <div>
    <!-- -->
    <Son>
      <template scope="scopeData">
        <ul>
          <li v-for="(item, index) in scopeData.games" :key="index">
            {{ item }}
          </li>
        </ul>
      </template>
    </Son>
    <Son>
      <template scope="scopeData">
        <ul>
          <h3 v-for="(item, index) in scopeData.games" :key="index">
            {{ item }}
          </h3>
        </ul>
      </template>
    </Son>
  </div>
</template>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值