vue插槽

12 篇文章 0 订阅

 

目录

 

插槽内容

编译作用域

后备内容

具名插槽

作用域插槽

动态插槽名

具名插槽缩写


插槽内容

组件之间的内容会替换slot标签

<navigation-link url="/profile">
  Your Profile
</navigation-link>

<a v-bind:href="url" class="nav-link">
  <slot></slot>
</a>

编译作用域

父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。

<navigation-link url="/profile">
  Logged in as {{ user.name }}
</navigation-link>

后备内容

slot之间为默认内容,父组件不提供插槽内容时,默认渲染

<button type="submit">
  <slot>Submit</slot>
</button>

具名插槽

name  v-slot:  默认default

注意 v-slot 只能添加在 <template> 上 (只有一种例外情况),这一点和已经废弃的 slotattribute 不同。

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


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

//或者

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

作用域插槽

slot上绑定之属性  v-slot:header="slotProps"

<span>
  <slot v-bind:user="user">
    {{ user.lastName }}
  </slot>
</span>

<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</current-user>
  • 独占默认插槽的缩写
<current-user v-slot:default="slotProps">
  {{ slotProps.user.firstName }}
</current-user>

或

<current-user v-slot="slotProps">
  {{ slotProps.user.firstName }}
</current-user>



<!--独占默认插槽不能和具名插槽混用 无效,会导致警告 -->
<current-user v-slot="slotProps">
  {{ slotProps.user.firstName }}
  <template v-slot:other="otherSlotProps">
    slotProps is NOT available here
  </template>
</current-user>
  • 解构插槽
<current-user v-slot="{ user }">
  {{ user.firstName }}
</current-user>

重命名:

<current-user v-slot="{ user: person }">
  {{ person.firstName }}
</current-user>


定义后备内容(默认值)


<current-user v-slot="{ user = { firstName: 'Guest' } }">
  {{ user.firstName }}
</current-user>

动态插槽名

<base-layout>
  <template v-slot:[dynamicSlotName]>
    ...
  </template>
</base-layout>

具名插槽缩写

<base-layout>
  <template #header>
    <h1>Here might be a page title</h1>
  </template>

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

  <template #footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值