VUE.js学习笔记(一)简单理解<slot>标签

本文介绍了Vue中slot和具名slot的使用。slot可理解为内存插槽,子组件提供<slot>标签,父组件提供插入内容。简单slot可替换父组件添加的内容,而具名slot可满足多插槽需求,可通过v - slot指令向具名插槽提供内容。

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

slot

官方称之为”插槽”,我理解就是像是内存插槽的意思,我在子组件里提供这么一个<slot>标签(相当于主板提供的内存插槽)至于插入什么内容(插几G的内存)那是父组件需要提供的(由主机配置决定)。举个栗子:
我们继续改造一下之前的<li-test>的案例:

<template>
<div>
    <input class = 'aaa' v-model.trim="inputValue"/>
    <button @click="handleSubmit">提交</button>
    <span>{{inputValue}}</span>
    <ul>
        <li-test 
            v-for="(item,index) of list" 
            :key="index"
            :content='item'
            :index='index'
            @delete='handleDelete'
        >显示的是传递到子组件中,循环出来的item内容哦</li-test>
    </ul>
    <!-- 即使 Alt 或 Shift 被一同按下时也会触发 -->
    <button @click.middle ="onClick">A</button>
</div>
</template>

我们改造了一下父组件,在调用子组件<li-test>的模板时在里面增加一段话

 

执行后,原来新加的话被替换了

 

执行后可以看出,展示的是模板里的内容,我们在父组件里加的其实已经被替换掉了,但如何让他显示呢?这就需要<slot>插槽啦
修改li-test.vue组件:

<template>
<div>
    <li class='aaa' @click="handleDelete">{{content}}</li>
    <slot></slot>
</div>
</template>

子组件模板中我们加入<slot>组件:

 

可以看到<slot>标签直接替换成了我们在父组件增加的话啦

具名slot

上面的例子描述了简单的slot标签如何使用,但是有些场景下一个slot可能不能满足我们的组件需求,对于这样的情况,<slot> 元素有一个特殊的特性:name。这个特性可以用来定义额外的插槽:

官网案例:

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

一个不带 name 的 <slot> 出口会带有隐含的名字“default”。
在向具名插槽提供内容的时候,我们可以在一个 <template> 元素上使用 v-slot 指令,并以 v-slot 的参数的形式提供其名称:
官网案例:

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

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

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

现在 <template> 元素中的所有内容都将会被传入相应的插槽。任何没有被包裹在带有 v-slot 的 <template> 中的内容都会被视为默认插槽的内容。我们也可以用v-slot:default 来表明默认插槽的内容:

<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>

备注:v-slot: 可以缩写为”#”,但是该缩写只有在其有参数的时候才可用,以下方法是不可取的:

<!-- 这样会触发一个警告 -->
<current-user #="{ user }">
  {{ user.firstName }}
</current-user>

如果你希望使用缩写的话,你必须始终以明确插槽名取而代之:

<current-user #default="{ user }">
  {{ user.firstName }}
</current-user>



作者:水云楼
链接:https://www.jianshu.com/p/004e70b4cbd2
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值