diff --git a/src/guide/composition-api-template-refs.md b/src/guide/composition-api-template-refs.md index f04674edc8..45fe8aec12 100644 --- a/src/guide/composition-api-template-refs.md +++ b/src/guide/composition-api-template-refs.md @@ -85,3 +85,66 @@ Composition API template refs do not have special handling when used inside `v-f } ``` + +## Watching Template Refs + +Watching a template ref for changes can be an alternative to the use of lifecycle hooks that was demonstrated in the previous examples. + +But a key difference to lifecycle hooks is that `watch()` and `watchEffect()` effects are run *before* the DOM is mounted or updated so the template ref hasn't been updated when the watcher runs the effect: + +```vue + + + +``` + +Therefore, watchers that use template refs should be defined with the `flush: 'post'` option. This will run the effect *after* the DOM has been updated and ensure that the template ref stays in sync with the DOM and references the correct element. + +```vue + + + +``` + +* See also: [Computed and Watchers](./reactivity-computed-watchers.html#effect-flush-timing) diff --git a/src/guide/reactivity-computed-watchers.md b/src/guide/reactivity-computed-watchers.md index 20c75b62fc..97f48ae241 100644 --- a/src/guide/reactivity-computed-watchers.md +++ b/src/guide/reactivity-computed-watchers.md @@ -123,7 +123,7 @@ In this example: - The count will be logged synchronously on initial run. - When `count` is mutated, the callback will be called **before** the component has updated. -In cases where a watcher effect needs to be re-run **after** component updates, we can pass an additional `options` object with the `flush` option (default is `'pre'`): +In cases where a watcher effect needs to be re-run **after** component updates (i.e. when working with [Template Refs](./composition-api-template-refs.md#watching-template-refs)), we can pass an additional `options` object with the `flush` option (default is `'pre'`): ```js // fire after component updates so you can access the updated DOM