可复用的组件
机器翻译
本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。
任务: 把一张卡片写一次,在任何页面上以不同的内容使用。
yaml
# Recipe: a reusable component with props and a slot, kept out of the URLs.
paths:
components: ./components组件也是一个 .q 文件。它的 q:param 就是它的 props,q:slot 是调用者的内容 放进去的地方。把它放在名字以 _ 开头的文件夹里:它可以被导入,但永远不会响应 URL。
xml
<q:component name="Card">
<!-- Props are q:params; the caller's content goes where q:slot is. -->
<q:param name="title" type="string" required="true" />
<q:param name="tone" type="string" default="plain" />
<section class="card card-{tone}">
<h2>{title}</h2>
<div class="card-body">
<q:slot />
</div>
</section>
</q:component>q:import 把它引入页面,<Card> 使用它。每个属性都是一个 prop,标签之间的内容 填入 slot,用页面的变量计算:
xml
<q:component name="Dashboard">
<!-- from="_shared": a folder whose name starts with _ is never a page. -->
<q:import component="Card" from="_shared" />
<q:set name="open" type="number" value="4" />
<html>
<body>
<Card title="Open tickets">
<p>{open} waiting for an answer.</p>
</Card>
<Card title="Warning" tone="alert">
<p>The mail server is slow today.</p>
</Card>
</body>
</html>
</q:component>xml
<q:test name="each card has its title and the page's content" page="/">
<test:visit />
<test:expect text="Open tickets 4 waiting for an answer." />
<test:expect text="Warning The mail server is slow today." />
</q:test>
<q:test name="a component in a _ folder is not a page" page="/_shared/Card">
<test:visit />
<test:expect status="404" />
</q:test>text
tests/cards.test.q
PASS each card has its title and the page's content
PASS a component in a _ folder is not a page
2 passed, 0 failed