Chuyển đến nội dung

Bài 11 · Components and Helpers

Components and Arguments

Build Ember components with the template tag format - template-only and class-based components, passing arguments, local state, getters and nesting - with runnable stand-ins.

A component is a reusable piece of the page: a button, a card, a comment list, a whole form. Components are the main way you build screens in Ember. A route's template places components, those components place other components, and so on, until you have the full page.

Real versus stand-in. The .gjs components below are real Ember code, read-only on this site. The runnable blocks model a component as a plain JavaScript function or class that returns HTML, so you can experiment with arguments and state without the Ember build system.

The smallest component

A component name is kebab-case in the file system (user-card) and PascalCase when you use it in a template (<UserCard />). With the template tag format, a component can be just a template:

JavaScript
// app/components/user-card.gjs
<template>
  <div class="user-card">
    <h3>{{@name}}</h3>
    <p>{{@role}}</p>
  </div>
</template>

Generate it with ember generate component user-card. Using it means importing it, because the template tag format is explicit about dependencies:

JavaScript
// app/templates/team.gjs
import UserCard from 'my-app/components/user-card';

<template>
  <UserCard @name="Ada Lovelace" @role="Mathematician" />
  <UserCard @name="Grace Hopper" @role="Admiral" />
</template>

Each @name is an argument (passed by the parent). A component with only a template, and no class, is called template-only. Prefer it whenever the component needs no state or logic; it is the cheapest kind.

Class-based components

Add a class when you need state, getters, actions or injected services. A Glimmer component extends Component from @glimmer/component:

JavaScript
// app/components/rental-card.gjs
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { on } from '@ember/modifier';

export default class RentalCard extends Component {
  @tracked isWide = false;

  get title() {
    return this.args.title.toUpperCase();
  }

  toggleSize = () => {
    this.isWide = !this.isWide;
  };

  <template>
    <article class={{if this.isWide "wide" "narrow"}}>
      <h3>{{this.title}}</h3>
      <p>{{@owner}}</p>
      <button type="button" {{on "click" this.toggleSize}}>
        {{if this.isWide "Make narrow" "Make wide"}}
      </button>
    </article>
  </template>
}

Key points:

  • this.args holds the arguments in JavaScript: this.args.title. In the template you write @title.
  • Arguments are read-only. Assigning to this.args.title throws. If the component needs an editable copy, keep it in a @tracked field.
  • State lives in @tracked fields on the class (isWide). Reassigning one updates the template.
  • A getter (title) derives a value from arguments or state.
  • toggleSize is an arrow function field, so this stays correct when it is used as an event handler. (@action is an alternative; see the next lesson.)
  • The constructor is rarely needed; prefer fields.

Arguments versus attributes

@name passes data to the component. A plain HTML attribute such as class or data-test-id is forwarded to an element when the component uses ...attributes (see Component Patterns):

JavaScript
<template>
  <UserCard @name="Ada" class="highlighted" data-test-user="ada" />
</template>

You can pass any JavaScript value as an argument: strings, numbers, booleans, objects, arrays and functions. Use mustaches for non-strings:

JavaScript
<template>
  <UserCard
    @name={{@user.name}}
    @tags={{array "math" "code"}}
    @isAdmin={{true}}
    @onSelect={{this.selectUser}}
  />
</template>

Passing a function (@onSelect) is how a child sends information back up: data down, actions up.

JS A component as a function of its arguments

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ember's tracking system likewise throws a clear error when code writes to this.args.

State and getters

Components keep their own state in tracked fields. This stand-in implements a card with a toggle using a class, a getter and a re-render function:

JS State, getter and re-render

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Nesting components

Components render other components. The parent passes down what the child needs:

JavaScript
// app/components/team-list.gjs
import UserCard from 'my-app/components/user-card';

<template>
  <section>
    <h2>{{@heading}}</h2>
    {{#each @members as |member|}}
      <UserCard @name={{member.name}} @role={{member.role}} />
    {{/each}}
  </section>
</template>

If a component lives in a subfolder (app/components/team/member.gjs), its template name is Team::Member in classic .hbs files; with .gjs you import it by path and use whatever local name you imported it under.

flowchart TD
  R["Route template"] --> TL["TeamList"]
  TL --> U1["UserCard (Ada)"]
  TL --> U2["UserCard (Grace)"]

A route template renders TeamList, which renders one UserCard per member.

Where do component files live?

Ember uses colocation: the template and class are in the same file (.gjs), or side by side (user-card.js and user-card.hbs) in older code. Keep one component per file, and put helpers of that component next to it. When a component grows large, split it into smaller ones; components are cheap.

When to create a component

  • The same markup appears twice or more.
  • A part of a page has its own state or behavior (a toggle, an accordion, a form field).
  • A route template grows past what you can read at a glance.

Do not create components just to wrap a single element with no purpose; and avoid putting data loading in them if a route could do it, because the router handles waiting and errors better (see Route Classes and the Model Hook).

Common mistakes

  • Writing to an argument. this.args.count++ fails; copy to a tracked field or call an action passed by the parent.
  • Forgetting the import. In .gjs files, a component not imported is "undefined" and the template fails to compile.
  • Using this in the template for an argument. An argument is @name, not this.name.
  • A name that is not PascalCase in the template. <user-card> is a plain HTML element; write <UserCard>.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. How do you read an argument called title inside a component class?

    Arguments are available as this.args in JavaScript, and as @title in the template.
  2. 2. When should a component be template-only?

    A template-only component is cheaper and simpler. Add a class only when you need state or behavior.
  3. 3. How do you write the component in app/components/user-card.gjs in a template?

    Components are invoked in PascalCase angle-bracket form, and with the template tag format they must be imported.
  4. 4. What happens if a child tries to assign to this.args.count?

    Data flows down. A child asks for a change by calling a function the parent passed.

Summary

  • A component is a template, optionally with a class; use PascalCase in templates and kebab-case file names.
  • Arguments (@name in templates, this.args.name in classes) are read-only and pass down.
  • State lives in @tracked fields; getters derive values; arrow-function fields or @action make handlers.
  • Template-only components are the default; add a class only when needed.
  • Parents pass functions as arguments so children can send actions up.

Next: Actions, Events and Forms

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.