Odd behavior with useTemplateRef
and watchEffect
/watch
#12989
Replies: 1 comment 3 replies
-
I think when the decision was made to make In that Playground you'll see the watchers get triggered twice, once for the change to By default, watchers are So with
With
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
This isn't really a bug as far as I understand it, but I wanted to make a post about it for discussion in case anyone (including my future self) ran into it.
Consider the following reduced test case:
The console logs won't log the expected array lengths. (But the arrays rendered in the
<template>
will).The first key is to recognize that while the
useTemplateRef
is reactive, it doesn't get updated with the correct/expected value until the new DOM elements associated with it are actually mounted: https://stackoverflow.com/questions/79031309/usetemplateref-is-not-reactive-for-arrays Meaning, anything tracking the ref will get called, but right before the value is updated to the expected value, not after as I would've expected. I guess this is because it's a shallow ref, not a deep one? And I guess they made it shallow as a prudent design decision to avoid infinite renders or something like that? If someone more knowledgeable could explain this in a less hand-wavy way, it would be appreciated.So you have to
await nextTick()
to get the expected value. But that introduces another odd problem when usingwatchEffect
. Regularwatch
works fine because you're manually providing the dependencies, but apparentlywatchEffect
cannot auto-track dependencies that are used asynchronously within the function:#2093 In my example above, if you un-comment the
console.log("watchEffect, sync"
, it will work as expected, but not if it's commented out and are thus only using the dependencies after theawait
.Beta Was this translation helpful? Give feedback.
All reactions