目录
插槽内容
组件之间的内容会替换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>
上 (只有一种例外情况),这一点和已经废弃的 slot
attribute 不同。
<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>