子组件:Vue 中的插槽(Slot)是一种组件化技术,可以在父组件中提供子组件所需要的内容。使用插槽可以使得组件的可复用性提高,使得父组件与子组件更加松耦合。
父组件:
<template>
<div>
<header>
<slot name="header">默认标题</slot>
</header>
<main>
<slot name="body">默认内容</slot>
</main>
</div>
</template>
子组件:
<template>
<div>
<h1>我的应用程序</h1>
<p>这是应用程序的内容。</p>
<my-component>
<h2 slot="header">这是子组件的标题。</h2>
<p slot="body">这是子组件的内容。</p>
</my-component>
</div>
</template>
在上面的例子中,父组件中引用了子组件,并使用了 slot
来提供子组件所需要的内容。slot
可以通过 name
属性来命名,这样子组件中就可以通过名称识别 content。子组件中使用 slot
标签来输出父组件提供的内容。
通过这种方式,我们可以提高组件的自定义性,使得父组件可以根据需要动态地传递内容给子组件。