vue slot插槽用法详解

文件示例

<template>
  <slot-style>
    <!-- 只要出现多个插槽,请始终为所有的插槽使用完整的基于 <template> 的语法: -->
    <template #default="scope">
      {{ scope.itemVal }}
    </template>
    <template #slotName3="scope2">
      {{ scope2.slotName }}{{ scope2.hai }}
    </template>
    <template #slotName> hello </template>
    <template #slotName2> world </template>
  </slot-style>
</template>

<script>
import slotStyle from "@/components/slotStyle.vue";
export default {
  components: { slotStyle },
  setup() {},
};
</script>```


子组件
```html
<template>
  <div v-for="item in arr" :key="item">
    <slot :itemVal="item"></slot>
  </div>
  <slot name="slotName3" :slotName="name" hai="嗨!"></slot>
  <slot name="slotName"></slot>
  <slot name="slotName2"></slot>
</template>



<script>
import { reactive, ref } from "vue";
export default {
  setup() {
    let arr = reactive([1, 2, 3, 4, 5]);
    let name = ref("你妈的逼");
    return { arr, name };
  },
};
</script>



# 作用简介
<slot> 元素作为承载分发内容的出口。
它允许你像这样合成组件:

```html
<todo-button>
  Add todo
</todo-button>

然后在 的模板中,你可能有:

<!-- todo-button 组件模板 -->
<button class="btn-primary">
  <slot></slot>
</button>

不过,字符串只是开始!插槽还可以包含任何模板代码,包括 HTML,已经其他组件

具名插槽

<div class="container">
  <header>
    <!-- 我们希望把页头放这里 -->
    <slot name="header"></slot>
  </header>
  <main >
   <slot></slot>
    <!-- 我们希望把主要内容放这里 -->
  </main>
  <footer>
  <slot name="foter"></slot>
    <!-- 我们希望把页脚放这里 -->
  </footer>
</div>

插槽写法

<base-layout>
  <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>

  <template v-slot:default>
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </template>

  <template v-slot:footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

作用域插槽

<ul>
  <li v-for="( item, index ) in items">
    <slot :item="item"></slot>
  </li>
</ul>
<todo-list>
  <template v-slot:default="slotProps">
    <i class="fas fa-check"></i>
    <span class="green">{{ slotProps.item }}</span>
  </template>
</todo-list>

具名插槽的缩写

看第一个例子 v-solt 可缩写成#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值