new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Vue · Tutorial · all subjects

computed and watchers

48 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

onWatcherCleanup() example

import { watch, onWatcherCleanup } from 'vue' watch(id, (newId) => { const { response, cancel } = doAsyncWork(newId) onWatcherCleanup(cancel) })

watch() getter example

const state = reactive({ count: 0 }) watch( () => state.count, (count, prevCount) => { /* ... */ } )

watch() ref example

const count = ref(0) watch(count, (count, prevCount) => { /* ... */ })

watch() multiple sources example

watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => { /* ... */ })

watch() deep mode with getter

When watching a getter source, the watcher only fires if the getter's return value has changed. To fire the callback even on deep mutations, explicitly force the watcher into deep mode with { deep: true }. In deep mode, the new value and old value will be the same object if the callback was triggered by a deep mutation. const state = reactive({ count: 0 }) watch( () => state, (newValue, oldValue) => { // newValue === oldValue }, { deep: true } )

watch() reactive object automatic deep mode

When directly watching a reactive object, the watcher is automatically in deep mode. const state = reactive({ count: 0 }) watch(state, () => { /* triggers on deep mutation to state */ })

watch() flush and debug options example

watch(source, callback, { flush: 'post', onTrack(e) { debugger }, onTrigger(e) { debugger } })

watch() stopping example

const stop = watch(source, callback) stop()

watch() pause and resume (3.5+)

const { stop, pause, resume } = watch(() => {}) pause() resume() stop()

watch() cleanup example

watch(id, async (newId, oldId, onCleanup) => { const { response, cancel } = doAsyncWork(newId) onCleanup(cancel) data.value = await response })

onWatcherCleanup() registers cleanup for watcher

onWatcherCleanup() (3.5+) registers a cleanup function to be executed when the current watcher is about to re-run. Can only be called during the synchronous execution of a watchEffect effect function or watch callback function, i.e. it cannot be called after an await statement in an async function.

onWatcherCleanup() type signature

function onWatcherCleanup(cleanupFn: () => void, failSilently?: boolean): void

computed() creates readonly or writable reactive refs

computed() takes a getter function and returns a readonly reactive ref object for the returned value. It can also take an object with get and set functions to create a writable ref object.

computed() type signatures

Read-only: function computed<T>(getter: (oldValue: T | undefined) => T, debuggerOptions?: DebuggerOptions): Readonly<Ref<Readonly<T>>>. Writable: function computed<T>(options: { get: (oldValue: T | undefined) => T, set: (value: T) => void }, debuggerOptions?: DebuggerOptions): Ref<T>.

computed() readonly example

const count = ref(1) const plusOne = computed(() => count.value + 1) console.log(plusOne.value) // 2 plusOne.value++ // error

computed() writable example

const count = ref(1) const plusOne = computed({ get: () => count.value + 1, set: (val) => { count.value = val - 1 } }) plusOne.value = 1 console.log(count.value) // 0

computed() debugging example

const plusOne = computed(() => count.value + 1, { onTrack(e) { debugger }, onTrigger(e) { debugger } })

watchEffect() runs function and tracks dependencies

watchEffect() runs a function immediately while reactively tracking its dependencies and re-runs it whenever the dependencies are changed.

watchEffect() type signature

function watchEffect(effect: (onCleanup: OnCleanup) => void, options?: WatchEffectOptions): WatchHandle. type OnCleanup = (cleanupFn: () => void) => void. interface WatchEffectOptions { flush?: 'pre' | 'post' | 'sync', onTrack?: (event: DebuggerEvent) => void, onTrigger?: (event: DebuggerEvent) => void }. interface WatchHandle { (): void, pause: () => void, resume: () => void, stop: () => void }.

watchEffect() effect function receives cleanup callback

The effect function receives a function that can be used to register a cleanup callback. The cleanup callback will be called right before the next time the effect is re-run and can be used to clean up invalidated side effects like a pending async request.

watchEffect() flush timing defaults to 'pre'

By default, watchers will run just prior to component rendering (flush: 'pre'). Setting flush: 'post' defers the watcher until after component rendering. Setting flush: 'sync' triggers the watcher immediately when a reactive dependency changes, but should be used with caution as it can lead to performance and data consistency problems.

watchEffect() return value stops the effect

The return value is a handle function that can be called to stop the effect from running again.

watchEffect() basic example

const count = ref(0) watchEffect(() => console.log(count.value)) // -> logs 0 count.value++ // -> logs 1

watchEffect() stopping example

const stop = watchEffect(() => {}) stop()

watchEffect() pause and resume (3.5+)

const { stop, pause, resume } = watchEffect(() => {}) pause() resume() stop()

watchEffect() cleanup example

watchEffect(async (onCleanup) => { const { response, cancel } = doAsyncWork(newId) onCleanup(cancel) data.value = await response })

watchEffect() options example

watchEffect(() => {}, { flush: 'post', onTrack(e) { debugger }, onTrigger(e) { debugger } })

watchPostEffect() is alias for watchEffect with flush 'post'

watchPostEffect() is an alias of watchEffect() with flush: 'post' option.

watchSyncEffect() is alias for watchEffect with flush 'sync'

watchSyncEffect() is an alias of watchEffect() with flush: 'sync' option.

watch() function watches reactive sources and invokes callback

watch() watches one or more reactive data sources and invokes a callback function when the sources change.

watch() type signatures

Single source: function watch<T>(source: WatchSource<T>, callback: WatchCallback<T>, options?: WatchOptions): WatchHandle. Multiple sources: function watch<T>(sources: WatchSource<T>[], callback: WatchCallback<T[]>, options?: WatchOptions): WatchHandle. type WatchCallback<T> = (value: T, oldValue: T, onCleanup: (cleanupFn: () => void) => void) => void. type WatchSource<T> = Ref<T> | (() => T) | (T extends object ? T : never).

watch() options type

interface WatchOptions extends WatchEffectOptions { immediate?: boolean (default: false), deep?: boolean | number (default: false), flush?: 'pre' | 'post' | 'sync' (default: 'pre'), onTrack?: (event: DebuggerEvent) => void, onTrigger?: (event: DebuggerEvent) => void, once?: boolean (default: false, 3.4+) }.

watch() is lazy by default

watch() is lazy by default, meaning the callback is only called when the watched source has changed.

watch() source types

The source can be one of the following: a getter function that returns a value, a ref, a reactive object, or an array of the above.

watch() callback arguments

The callback receives three arguments: the new value, the old value, and a function for registering a side effect cleanup callback. The cleanup callback will be called right before the next time the effect is re-run and can be used to clean up invalidated side effects like a pending async request. When watching multiple sources, the callback receives two arrays containing new / old values corresponding to the source array.

watch() options explained

immediate: trigger the callback immediately on watcher creation, old value will be undefined on first call. deep: force deep traversal of the source if it is an object so the callback fires on deep mutations, in 3.5+ can be a number indicating max traversal depth. flush: adjust callback's flush timing. onTrack / onTrigger: debug the watcher's dependencies. once: (3.4+) run the callback only once, watcher is automatically stopped after first callback run.

watch() advantages over watchEffect()

Compared to watchEffect(), watch() allows performing the side effect lazily, being more specific about what state should trigger the watcher to re-run, and accessing both the previous and current value of the watched state.

Writable computed properties with get and set

A computed property can be made writable by providing both get and set methods in an object. The get method returns the computed value, and the set method receives the new value being assigned.

computed getter receives previous value parameter

A computed getter function can optionally receive a third parameter, previous, which contains the previously computed value.

Arrow functions with computed properties lose this context

If an arrow function is used with a computed property, this will not point to the component's instance. However, the instance can still be accessed as the function's first argument: computed: { aDouble: (vm) => vm.a * 2 }

watch option watches reactive properties

The watch option is an object where keys are reactive component instance properties to watch (e.g., properties declared via data or computed) and values are the corresponding callbacks. The callback receives the new value and the old value of the watched source.

watch supports dot-delimited nested property paths

In addition to root-level properties, watch keys can be dot-delimited paths like 'a.b.c'. However, this only supports simple dot-delimited paths and does not support complex expressions. For complex data sources, use the imperative $watch() API instead.

watch value can be string method name or callback

The watch value can be a string referring to a method name (declared via methods), a direct callback function, or an object containing additional options with a handler field.

watch options: immediate, deep, flush, onTrack, onTrigger

Watch options include: immediate (boolean, default false, triggers callback immediately on watcher creation with undefined old value), deep (boolean, default false, forces deep traversal for deep mutations), flush (string 'pre' | 'post' | 'sync', default 'pre', adjusts callback flush timing), onTrack (function for debugging), onTrigger (function for debugging).

watch callback receives onCleanup function

Watch callbacks receive three parameters: value (new value), oldValue (old value), and onCleanup (a function that accepts a cleanup function to be called before the watcher fires again or is destroyed).

watch supports array of multiple callbacks

The watch value can be an array of callbacks, which will be called one by one. Each callback can be a string method name, a function, or an object with handler and options.

Avoid arrow functions when declaring watch callbacks

Do not use arrow functions when declaring watch callbacks because arrow functions will not have access to the component instance via this.

computed properties are read-only by default

Computed properties are declared as an object where the key is the computed property name and the value is either a computed getter function or an object with get and set methods. By default, computed properties are read-only and only have a getter.

Give your agent this brain