Vue3.2插槽全家桶

1.新建一个组件,在主页面中引入该主页,在组件中建立需要的插槽,然后在主页面中插入相应的内容,具体代码解释如下↓
匿名插槽和具名插槽
<template>
<!-- 主页面 -->
  <div class="container">
    <h1>我是插槽</h1>
    <slotCom>
      <!-- 具名插槽 #这是语法糖 也可以使用v-solt:name的方式-->
      <template #header>
        我往盒子上面插入
      </template>
     <!-- 匿名插槽 -->
      <template v-slot>
          我往盒子中间插入
      </template>

      <!-- 具名插槽 -->
      <template #footer>
        我往盒子下方插入
      </template>
    </slotCom>
  </div>
</template>

<script setup>
import { reactive, toRefs } from 'vue'
import slotCom from '@/components/slotCom'

</script>

<style lang="scss" scoped>

</style>


子页面
<template>
  <div>
    我是头,我使用的是具名插槽
    <slot name="header"></slot>
  </div>
  <div>
    我是中间,我使用的是匿名插槽
    <slot></slot>
  </div>
  <div>我是尾,我也用的是具名插槽
    <slot name="footer"></slot>
  </div>
</template>

<script setup>
import { reactive, toRefs } from 'vue'

</script>

<style lang="scss" scoped>
div {
  width: 90%;
  height: 100px;
  margin-left: 5%;
  line-height: 100px;
  border: 1px solid rgb(0, 0, 0);
  margin-bottom: 10px;
  text-align: center;
}
</style>
2.下面我们来看看作用域插槽,是子组件像父组件传递数据,从而填充父组件的内容
//这里是子组件
<template>
  <div>
      这里是作用域插槽
    <span v-for="(item, index) in data" :key="index">
    <!-- 可以插入多个数据 -->
        <slot :data="item" :index="index"></slot>
    </span>
  </div>
</template>

<script setup>
import { reactive, toRefs } from 'vue'

const data = reactive([
  { name: '作用域插槽来咯1', age: 201 },
  { name: '作用域插槽来咯2', age: 202 },
  { name: '作用域插槽来咯3', age: 203 },
])

</script>

<style lang="scss" scoped>
div {
  width: 90%;
  margin-left: 5%;
  line-height: 100px;
  border: 1px solid rgb(0, 0, 0);
  margin-bottom: 10px;
  text-align: center;
}
</style>

//这里是父组件接收
<template>
<!-- 主页面 -->
  <div class="container">
      <!-- 可简写为#default -->
      <template v-slot="{data,index}">
          <p>{{index}}---{{data.name}}----{{data.age}}</p>
      </template>
      
    </slotCom>
  </div>
</template>

<script setup>
import { reactive, toRefs } from 'vue'
import slotCom from '@/components/slotCom'

</script>

<style lang="scss" scoped>

</style>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值