vue里插槽详解与使用

首先插槽分为匿名插槽、具名插槽和作用域插槽

先准备两个页面和一个组件

list.vue组件

<template>
  <div>
    <div>组件内容区域1</div>
    <div>组件内容区域2</div>
  </div>
</template>

a.vue页面

<script setup>
import List from './components/list.vue'
</script>
<template>
  <div class="content">
    这是aaa页面
    <List></List>
  </div>
</template>

b.vue页面

<script setup>
import List from './components/list.vue'
</script>
<template>
  <div class="content">
    这是bbb页面
    <List></List>
  </div>
</template>

然后我们在list组件中使用插槽

<template>
  <div>
    <div>组件内容区域1</div>
    <div>组件内容区域2</div>
    <slot></slot> 
  </div>
</template>

此时页面还没有什么变化,我们修改a页面

<script setup>
import List from './components/list.vue'
</script>
<template>
  <div class="content">
    这是aaa页面
    <List>
      <div style="color: red;">给插槽插入内容</div>
    </List>
  </div>
</template>

然后运行a页面效果

b页面效果

如果我们想在组件里其他位置再插入内容,就可以使用具名插槽了

修改a页面

<script setup>
import List from './components/list.vue'
</script>
<template>
  <div class="content">
    这是aaa页面
    <List>
      <template #header>
        <div style="color: red;">在组件顶部插入内容</div>
      </template>
      <template #footer>
        <div style="color: red;">给组件底部插入内容</div>
      </template>
      
    </List>
  </div>
</template>

修改list组件

<template>
  <div>
    <slot name="header"></slot> 
    <div>组件内容区域1</div>
    <div>组件内容区域2</div>
    <slot name="footer"></slot> 
  </div>
</template>

a页面运行效果

作用域插槽就是在具名插槽上再传入值,比如我们想要在b页面显示list里的数据,需要list组件将值传给b页面

修改b页面和list组件

<script setup>
import List from './components/list.vue'
</script>
<template>
  <div class="content">
    这是bbb页面
    <List>
      <template #footer="{arr}">
        <div v-for="(item, index) in arr" :key="index">{{ item }}</div>
      </template>
    </List>
  </div>
</template>
<script setup>
  import { ref } from 'vue'
  const arr=ref(['a','b','c','d'])
</script>
<template>
  <div>
    <slot name="header"></slot> 
    <div>组件内容区域1</div>
    <div>组件内容区域2</div>
    <slot name="footer" :arr="arr"></slot> 
  </div>
</template>

b页面效果如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值