liveBook · Manning

Computed property

As explained in Web Component Development with Modern Libraries and Tooling

A wrec component property whose value is defined by an expression and recomputed when its dependencies change.

A computed property defines its value with an expression and updates automatically when the properties it uses change. In wrec, this avoids lifecycle code for derived values such as an area. section 8.3 section 8.7

Area calculator

Declare width, height, and area together: area uses the expression this.width * this.height. Bind sliders to width and height, then display this.area; changing either slider recalculates the displayed area. section 8.7

Choose the simplest representation that fits the calculation:

  • Use an inline template expression for a simple value such as this.width * this.height. section 8.3
  • Use a computed property when the derived value deserves a named property or the expression is more complex. section 8.3
  • Use a method when computation needs procedural code; declare usedBy dependencies so wrec knows when to reevaluate it. section 8.3
Listing 8.5 area-calculator.ts
import { css, html, Wrec } from "wrec";

// Insert makeSlider function from listing 8.6 here.

class AreaCalculator extends Wrec {
  static properties = {
    width: { type: Number, value: 1 },
    height: { type: Number, value: 1 },
    area: { type: Number, computed: "this.width * this.height" },
  };

  static css = css`
    div {
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }
    label {
      display: inline-block;
      width: 3rem;
      text-align: right;
    }
  `;

  static html = html`
    <div>${makeSlider("Width", "width")}</div>
    <div>${makeSlider("Height", "height")}</div>
    <div>
      <label>Area</label>
      <span>this.area</span>
    </div>
  `;
}

AreaCalculator.define("area-calculator");

Inspect a complete area calculator that combines a computed property, slider bindings, and rendered output. section 8.7

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Explains declaration, recomputation, and alternatives, but does not detail the runtime dependency-tracking internals.
Examples
Uses width and height sliders to compute and display a rectangle area.
What you can do after
Apply it via wrec by declaring a computed property and displaying its value in component markup.
How it connects
Connects computed properties with component properties, template expressions, two-way binding, methods, and lifecycle methods.

Also explained in

Compare how 3 books explain computed property →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.