vue插槽、具名插槽、作用域插槽

本文深入讲解Vue中的插槽使用,包括普通插槽、具名插槽及作用域插槽的概念与实践,帮助开发者掌握组件间内容传递的技巧。

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

vue插槽的使用

my-component组件

<template>
  <div>
    hello
  </div>
</template>
<script>
export default {
  name: 'MyComponent'
}
</script>

父组件使用my-component组件

<template>
  <div>
    <my-component>
      world
    </my-component>
  </div>
</template>

<script>
import MyComponent from './MyComponent'
export default {
  name: 'Test',
  components: { MyComponent },
  data() {
    return {
    }
  }
}
</script>

如上,使用my-component组件时,在父组件中直接添加内容,输出结果如下:
在这里插入图片描述

若想在子组件中插入内容,这时候就需要用到插槽,我们做如下改变

普通插槽

my-component

<template>
  <div>
    hello
    <slot>这里可以添加没有使用插槽时默认显示的内容</slot>
  </div>
</template>

<script>
export default {
  name: 'MyComponent'
}
</script>

此时页面显示:
在这里插入图片描述

由此可见,插槽得作用就是为了在使用组件时添加额外得内容。上面用的时默认普通插槽。

具名插槽

具名插槽顾名思义就是具体名称的插槽,当组件中添加多个插槽的时候就要对插槽进行区分,这时候就要给插槽起名字,

my-component

<template>
  <div>
    hello
    <slot name="dream"></slot>
  </div>
</template>

<script>
export default {
  name: 'MyComponent'
}
</script>

父组件

<template>
  <div>
    <my-component>
      <p slot="world">world</p>
      <p slot="dream"> dream</p>
    </my-component>
  </div>
</template>

<script>
import MyComponent from './MyComponent'
export default {
  name: 'Test',
  components: { MyComponent },
  data() {
    return {
    }
  }
}
</script>

最终显示

在这里插入图片描述

可以看出,当使用多个插槽的时候,根据name可以选择性显示不能内容。

作用域插槽

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值