在 Vue.js 中,插槽(slot)是一种非常强大的功能,它允许我们定义组件模板的某些部分,而这些部分的内容将由父组件来决定。这对于创建可复用的组件非常有用,因为你可以定义组件的结构,但将具体的内容留给使用它的父组件来填充。
基本插槽
Vue.js 提供了默认插槽和具名插槽两种类型。
默认插槽
默认插槽是最简单的插槽形式,它不需要命名。当组件中只有一个插槽时,默认插槽就会被使用。
子组件(ChildComponent.vue):
<template>
<div>
<h2>我是子组件的标题</h2>
<!-- 默认插槽 -->
<slot></slot>
</div>
</template>
<script>
export default {
name: 'ChildComponent'
}
</script>
父组件:
<template>
<div>
<ChildComponent>
<!-- 这里的内容会被渲染到子组件的<slot>位置 -->
<p>这是父组件传递给子组件的内容</p>
</ChildComponent>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
}
}
</script>
具名插槽
当组件中有多个插槽时,我们需要给插槽命名(即具名插槽),以便区分它们。
子组件(ChildComponent.vue):
<template>
<div>
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot> <!-- 默认插槽 -->
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>
<script>
export default {
name: 'ChildComponent'
}
</script>
父组件:
<template>
<div>
<ChildComponent>
<template v-slot:header>
<h1>这是头部内容</h1>
</template>
<p>这是默认插槽的内容</p>
<template v-slot:footer>
<p>这是底部内容</p>
</template>
</ChildComponent>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
}
}
</script>
作用域插槽
作用域插槽是一种特殊类型的插槽,它允许子组件将数据“回传”给插槽的内容。这意呀着父组件可以访问到子组件的数据。
子组件(ChildComponent.vue):
<template>
<ul>
<li v-for="item in items" :key="item.id">
<slot name="item" :item="item"></slot>
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
]
}
}
}
</script>
父组件:
<template>
<ChildComponent>
<template v-slot:item="slotProps">
<span>{{ slotProps.item.text }}</span>
</template>
</ChildComponent>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
}
}
</script>
在作用域插槽中,slotProps
是一个对象,包含了传递给插槽的所有属性(在这个例子中是 item
)。通过这种方式,父组件可以访问到子组件的 items
数组中的每个元素,并在插槽的内容中使用它们。