# Dados Computados e Observadores
Esta seção usa a sintaxe de Componentes Single-File para exemplos de código
# computed
Recebe uma função getter e retorna um objeto ref reativo imutável para o valor retornado do getter.
const count = ref(1)
const plusOne = computed(() => count.value + 1)
console.log(plusOne.value) // 2
plusOne.value++ // erro
2
3
4
5
6
Alternativamente, ele pode usar um objeto com as funções get
e set
para criar um objeto ref gravável.
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
2
3
4
5
6
7
8
9
10
Tipando:
// somente leitura
function computed<T>(
getter: () => T,
debuggerOptions?: DebuggerOptions
): Readonly<Ref<Readonly<T>>>
// gravável
function computed<T>(
options: {
get: () => T
set: (value: T) => void
},
debuggerOptions?: DebuggerOptions
): Ref<T>
interface DebuggerOptions {
onTrack?: (event: DebuggerEvent) => void
onTrigger?: (event: DebuggerEvent) => void
}
interface DebuggerEvent {
effect: ReactiveEffect
target: any
type: OperationTypes
key: string | symbol | undefined
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# watchEffect
Executa uma função imediatamente enquanto rastreia reativamente suas dependências e a executa novamente sempre que as dependências são alteradas.
const count = ref(0)
watchEffect(() => console.log(count.value))
// -> loga 0
setTimeout(() => {
count.value++
// -> loga 1
}, 100)
2
3
4
5
6
7
8
9
Tipando:
function watchEffect(
effect: (onInvalidate: InvalidateCbRegistrator) => void,
options?: WatchEffectOptions
): StopHandle
interface WatchEffectOptions {
flush?: 'pre' | 'post' | 'sync' // default: 'pre'
onTrack?: (event: DebuggerEvent) => void
onTrigger?: (event: DebuggerEvent) => void
}
interface DebuggerEvent {
effect: ReactiveEffect
target: any
type: OperationTypes
key: string | symbol | undefined
}
type InvalidateCbRegistrator = (invalidate: () => void) => void
type StopHandle = () => void
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Ver também: Guia do watchEffect
# watchPostEffect
3.2+
Apelido de watchEffect
com a opção flush: 'post'
.
# watchSyncEffect
3.2+
Apelido de watchEffect
com a opção flush: 'sync'
.
# watch
A API do watch
é o equivalente exato da API de Opções this.$watch (e a opção watch correspondente). watch
requer a observação de uma fonte de dados específica e aplica efeitos colaterais em uma função callback separada. Também é preguiçoso por padrão - ou seja, o callback só é chamado quando a fonte monitorada é alterada.
Comparado com watchEffect,
watch
nos permite:- Executar o efeito colateral preguiçosamente;
- Ser mais específico sobre qual estado deve fazer com que o observador seja executado novamente;
- Acessar o valor anterior e o atual do estado observado.
# Observando uma Única Fonte
A fonte de dados do observador pode ser uma função getter que retorna um valor ou diretamente um ref:
// observando um getter
const state = reactive({ count: 0 })
watch(
() => state.count,
(count, prevCount) => {
/* ... */
}
)
// observando diretamente uma ref
const count = ref(0)
watch(count, (count, prevCount) => {
/* ... */
})
2
3
4
5
6
7
8
9
10
11
12
13
14
# Observando Várias Fontes
Um observador também pode observar várias fontes ao mesmo tempo usando um array:
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
/* ... */
})
2
3
# Comportamento Compartilhado com watchEffect
watch
compartilha comportamento com watchEffect
em termos de interrupção manual, invalidação de efeito colateral (com onInvalidate
passado para o callback como o terceiro argumento), momento de limpeza e depuração.
Tipando:
// observando uma única fonte
function watch<T>(
source: WatcherSource<T>,
callback: (
value: T,
oldValue: T,
onInvalidate: InvalidateCbRegistrator
) => void,
options?: WatchOptions
): StopHandle
// observando várias fontes
function watch<T extends WatcherSource<unknown>[]>(
sources: T
callback: (
values: MapSources<T>,
oldValues: MapSources<T>,
onInvalidate: InvalidateCbRegistrator
) => void,
options? : WatchOptions
): StopHandle
type WatcherSource<T> = Ref<T> | (() => T)
type MapSources<T> = {
[K in keyof T]: T[K] extends WatcherSource<infer V> ? V : never
}
// veja a tipagem de `watchEffect` para opções compartilhadas
interface WatchOptions extends WatchEffectOptions {
immediate?: boolean // default: false
deep?: boolean
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Ver também: Guia do watch