Skip to content

computed()

Okku edited this page May 31, 2021 · 4 revisions

When you want to compute new values from one or more reactive value, you'll want to use the computed method. The method takes a callback and returns a new ReadonlyReactivePrimitive whose value is updated with the return value of the callback whenever any of the reactive values used in the callback are updated.

Example:

const a = reactive(42); // ReactivePrimitive<number>, current value 42
const b = reactive(13); // ReactivePrimitive<number>, current value 13
const c = computed(() => a.value + b.value); // ReadonlyReactivePrimitive<number>, current value 55

a.value++; // 43
b.value *= 3; // 39

console.log(c.value); // 82

Computed strings

The computed method has a second overload that allows it to be used for templating computed strings:

const foo = reactive("foo");
const bar = reactive("bar");
const str = computed`${foo}${bar}`;

console.log(str); // "foobar"

← Previous: §1.4 reactive() | Next: §2 Templating →