实现步骤
- 在子组件中定义具名插槽,用来接收不同部分的内容。
- 在父组件中,通过
<template>
标签并指定v-slot
指令,将不同的内容对应到子组件的具名插槽中。
代码示例
子组件(PageLayout.vue)
<template>
<div>
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
父组件(App.vue)
<template>
<div id="app">
<PageLayout>
<template v-slot:header>
<h1>这是页眉</h1>
</template>
<p>这是主体内容</p>
<template v-slot:footer>
<p>这是页脚</p>
</template>
</PageLayout>
</div>
</template>
<script>
import PageLayout from './components/PageLayout.vue';
export default {
name: 'App',
components: {
PageLayout
}
};
</script>