插槽可以帮助你构建灵活和可复用的组件,分别有基本插槽、具名插槽和作用域插槽。
1.基本使用:
子组件:
<template>
<div class="child">
<h3>Child Component</h3>
<slot></slot> 放置插槽的位置
</div>
</template>
父组件
<child-component>
<p>This is the content from the parent component.</p>
</child-component>
2.具名插槽
子组件
<template>
<div class="child">
<h3>Child Component</h3>
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
父组件
<template>
<div class="parent">
<h1>Parent Component</h1>
<child-component>
<template v-slot:header>
<h2>This is the header content.</h2>
</template>
<template v-slot:default>
<p>This is the default content.</p>
</template>
<template v-slot:footer>
<p>This is the footer content.</p>
</template>
</child-component>
</div>
</template>
3. 作用域插槽
作用域插槽允许你将数据从子组件传递到插槽中,使得父组件可以使用这些数据。这对于需要在插槽中使用子组件数据的场景非常有用。
子组件
<template>
<div>
<h1>我是子组件</h1>
<div>
<h1 if="isshow===1">显示</h1>
<h1 else>隐藏</h1>
</div>
<slot></slot>
<!-- 具名插槽 -->
<slot name="name"></slot>
<slot :user="user"></slot>
</div>
</template>
<script>
export default {
data() {
return {
isshow: 1,
user: {
name: 'John Doe',
age: 25
}
}
}
}
</script>
<style>
</style>
总结
- 基本插槽:用于简单的内容插入。
- 具名插槽:用于在子组件中定义多个插槽,父组件可以通过名字插入不同内容。
- 作用域插槽:用于将子组件的数据传递给插槽,父组件可以使用这些数据。