Componentes reutilizables
Traducción automática
Esta página se tradujo automáticamente del inglés y todavía no la revisó un hablante nativo; las correcciones son bienvenidas en GitHub. Si algo no coincide, vale el original en inglés.
Tarea: escribir una tarjeta una vez y usarla en cualquier página, con contenido distinto.
yaml
# Recipe: a reusable component with props and a slot, kept out of the URLs.
paths:
components: ./componentsUn componente también es un archivo .q. Sus q:params son sus props, y q:slot es donde va el contenido de quien lo usa. Guárdalo en una carpeta cuyo nombre empieza con _: se puede importar, y nunca responde a una 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 lo trae a la página, y <Card> lo usa. Cada atributo es una prop, y el contenido entre las etiquetas llena el slot, calculado con las variables de la página:
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