插槽基本使用
通过代码看下插槽的基本使用:
---
import Header from './Header.astro';
import Logo from './Logo.astro';
import Footer from './Footer.astro';
const { title } = Astro.props;
---
<div id="content-wrapper">
<Header />
<Logo />
<h1>{title}</h1>
<slot /> <!-- 子项会在这 -->
<Footer />
</div>
---
import Wrapper from '../components/Wrapper.astro';
---
<Wrapper title="Fred 的页面">
<h2>关于 Fred 的一切</h2>
<p>这里有一些关于 Fred 的东西。</p>
</Wrapper>
可以看出Astro中的插槽和vue中插槽概念基本一致,这里也可以给插槽命名;
插槽命名
---
import Header from './Header.astro';
import Logo from './Logo.astro';
import Footer from './Footer.astro';
const { title } = Astro.props;
---
<div id="content-wrapper">
<Header />
<slot name="after-header" /> <!-- 带有 `slot="after-header"` 属性的子项在这 -->
<Logo />
<h1>{title}</h1>
<slot /> <!-- 没有 `slot` 或有 `slot="default"` 属性的子项在这 -->
<Footer />
<slot name="after-footer" /> <!-- 带有 `slot="after-footer"` 属性的子项在这 -->
</div>
这样就可以将不同的组件,放入不同插槽了
---
import Wrapper from '../components/Wrapper.astro';
---
<Wrapper title="弗雷德的页面">
<img src="<https://my.photo/fred.jpg>" slot="after-header" />
<h2>关于弗雷德的一切</h2>
<p>这里有一些关于弗雷德的资料。</p>
<p slot="after-footer">版权所有 2022</p>
</Wrapper>
插槽传递内容
---
// 创建一个自定义的表格,为头部和主体内容设置具名的 slot 占位符
---
<table class="bg-white">
<thead class="sticky top-0 bg-white"><slot name="header" /></thead>
<tbody class="[&_tr:nth-child(odd)]:bg-gray-100"><slot name="body" /></tbody>
</table>
---
import CustomTable from './CustomTable.astro';
---
<CustomTable>
<Fragment slot="header"> <!-- 传递表头 -->
<tr><th>产品名称</th><th>库存单位</th></tr>
</Fragment>
<Fragment slot="body"> <!-- 传递表格主体 -->
<tr><td>人字拖</td><td>64</td></tr>
<tr><td>靴子</td><td>32</td></tr>
<tr><td>运动鞋</td><td class="text-red-500">0</td></tr>
</Fragment>
</CustomTable>
设置插槽默认显示
---
import Header from './Header.astro';
import Logo from './Logo.astro';
import Footer from './Footer.astro';
const { title } = Astro.props;
---
<div id="content-wrapper">
<Header />
<Logo />
<h1>{title}</h1>
<slot>
<p>当没有子项传入插槽时使用此回退</p>
</slot>
<Footer />
</div>
## 这里在没有匹配的元素传递 slot=“name” 属性给具名插槽时,回退内容才会显示。
传递插槽
---
---
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<slot name="head" />
</head>
<body>
<slot />
</body>
</html>
## 使用
---
import BaseLayout from "./BaseLayout.astro";
---
<BaseLayout>
<slot name="head" slot="head" />
<slot />
</BaseLayout>