Article directory
1. Slot
Slots are a Vue
mechanism for defining reusable content in components. It allows you to distribute the content of a component to its subcomponents, making the component more 灵活性
functional 可重用性
. Vue3
The slots in are called “模板插槽”
and require new syntax when used. The specific usage is as follows:
1.1. Anonymous slots
In a child component, we can define a slot using <slot>
the tag :
<!-- Parent.vue -->
<template>
<div>
<slot></slot>
</div>
</template>
In the parent component, we can use <template>
the tag to insert into the slot defined in the parent component:
<!-- Child.vue -->
<template>
<Parent>
<!-- 这里是插槽内容 -->
<div>我是插槽内容</div>
</Parent>
</template>
This way, at runtime, the slot content replaces the content inside <slot>
the tag .
1.2. Named slots
If we define multiple slots in a component, we can use named slots to distinguish them:
<!-- Parent.vue -->
<template>
<div>
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
In child components, we can use v-slot
the directive to insert named slots:
<!-- Child.vue -->
<template>
<Parent>
<!-- 这里是具名插槽内容 -->
<template v-slot:header>
<h1>这里是头部</h1>
</template>
<!-- 这里是默认插槽内容 -->
<div>这里是中间部分</div>
<!-- 这里是具名插槽内容 -->
<template v-slot:footer>
<h1>这里是底部</h1>
</template>
</Parent>
</template>
v-slot
There is a corresponding abbreviation #
, so <template v-slot:header>
it can be abbreviated as <template #header>
. It means "pass this part of the template fragment into header
the slot of the parent component".
1.3. Scoped slots
Scoped slots allow parent components to pass data to the slot, making that data available to child components. In the parent component, we can use v-bind:名称="数据"
to pass data, and in the child component v-slot
directive to receive data:
<!-- Parent.vue -->
<template>
<div>
<slot v-bind:item="item" v-for="item in items"></slot>
</div>
</template>
In child components, we can use v-slot
the directive to insert scoped slots:
<!-- Child.vue -->
<template>
<Parent>
<!-- 这里是作用域插槽内容 -->
<template v-slot="{ item }">
<div>{
{ item }}</div>
</template>
</Parent>
</template>
This way, at runtime, each element in items
the array will be passed to the child component's scoped slot.