Vue.js 中的插槽(Slots)是Vue组件间进行内容传递的重要机制,用于在父组件中向子组件插入内容。以下是各类插槽的解释和用法:
-
默认插槽(Default Slot): 默认插槽是没有明确命名的插槽,它用于接收父组件传递的所有未指定插槽名的内容。在子组件中用
<slot>
标签表示。1<!-- 子组件 --> 2<template> 3 <div class="child-component"> 4 <h3>标题</h3> 5 <slot></slot> <!-- 这是默认插槽,用于插入父组件的内容 --> 6 </div> 7</template> 8 9<!-- 父组件 --> 10<template> 11 <ChildComponent> 12 <p>这是插入到子组件的默认插槽内容。</p> 13 </ChildComponent> 14</template>
-
匿名插槽。实际上在Vue中,默认插槽就是匿名插槽,即没有指定名称的插槽。所以前面对默认插槽的解释也包含了匿名插槽的概念。也就是说,当我们在子组件中看到这样的代码
<slot></slot>
,它就是一个匿名插槽,也就是默认插槽。<!-- 子组件 --> <template> <div class="child-component"> <h3>标题</h3> <slot> <!-- 这是匿名插槽(默认插槽) --> <!-- 如果父组件没有传入内容,则显示这里的默认内容 --> <p>这里是默认插槽的默认内容</p> </slot> </div> </template> <!-- 父组件 --> <template> <ChildComponent> <!-- 这里的内容会被插入到子组件的匿名插槽中 --> <p>这是插入到子组件的默认插槽内容。</p> </ChildComponent> </template>
3. 具名插槽(Named Slots): 具名插槽允许开发者为插槽赋予特定的名字,从而在子组件中精确放置内容。在子组件中通过 name
属性标记具名插槽。
1<!-- 子组件 -->
2<template>
3 <div class="child-component">
4 <header>
5 <slot name="header"></slot> <!-- 这是一个名为 header 的具名插槽 -->
6 </header>
7 <main>
8 <slot></slot> <!-- 这仍然是默认插槽 -->
9 </main>
10 <footer>
11 <slot name="footer"></slot> <!-- 这是一个名为 footer 的具名插槽 -->
12 </footer>
13 </div>
14</template>
15
16<!-- 父组件 -->
17<template>
18 <ChildComponent>
19 <template v-slot:header>
20 <h1>头部内容</h1>
21 </template>
22
23 <p>这是主内容区域</p>
24
25 <template v-slot:footer>
26 <p>底部内容</p>
27 </template>
28 </ChildComponent>
29</template>
-
作用域插槽(Scoped Slots): 作用域插槽可以让父组件访问子组件的数据并在插槽中使用。子组件可以将数据作为插槽 props 提供给父组件,然后父组件在渲染插槽内容时可以使用这些数据。
1<!-- 子组件 --> 2<template> 3 <div class="child-component"> 4 <ul> 5 <li v-for="item in items"> 6 <slot :item="item"> <!-- 作用域插槽,将items数组中的每一项传递给父组件 --> 7 {{ item.text }} <!-- 如果父组件没有提供作用域插槽,则显示此处的默认内容 --> 8 </slot> 9 </li> 10 </ul> 11 </div> 12</template> 13 14<script> 15export default { 16 data() { 17 return { 18 items: [ 19 { text: 'Item 1' }, 20 { text: 'Item 2' }, 21 ], 22 }; 23 }, 24}; 25</script> 26 27<!-- 父组件 --> 28<template> 29 <ChildComponent> 30 <template v-slot:item="slotProps"> 31 <b>{{ slotProps.item.text }}</b> 32 </template> 33 </ChildComponent> 34</template>
-
插槽默认值: Vue 2.x 版本中,如果一个插槽没有内容插入,可以为其设置默认值。在 Vue 3.x 版本中,通过
<slot>
标签的v-slot
缩写语法(#default
)可以设置默认插槽的内容。1<!-- Vue 2.x 的默认插槽默认值 --> 2<slot><p>这是一个默认插槽的默认内容</p></slot> 3 4<!-- Vue 3.x 设置默认插槽默认值 --> 5<template #default="{ fallback }"> 6 <p v-if="!fallback">这是一个默认插槽的默认内容</p> 7 <slot v-else></slot> 8</template>
在 Vue 3.x 中,可以利用
v-slot
的fallback
参数检测是否有内容插入,若无,则显示默认内容。注意Vue 3.x 中不再直接在<slot>
标签内设置默认值,而是通过判断条件来处理。