0👍
I don’t remember the exact sources, but I came across code like this:
const stopWatch = watch(helloworld, value => {
if (value) {
stopWatch();
// TODO: Start using the element
}
}, { immediate: true });
The problem is that when the current component is finished mounting, the child component may not yet have time to be mounted.
As part of a more reasonable description, you can wrap it all in a function:
function onRefReady (ref, cb) {
const stopWatch = watch(ref, value => {
if (value) {
stopWatch();
cb(value);
}
}, { immediate: true });
onScopeDispose(stopWatch);
}
And use it like this:
onRefReady(helloworld, el => {
// TODO: Start using the element
})
In short, according to the written code:
watch(ref, fn)
— callsfn
every time the value ofref
changes. Returns the function (stopWatch
) thatwatch
call will terminate.{ immediate: true }
— says to run the passed function immediately, in caseref
already has a non-empty value.onScopeDispose(stopWatch)
— says to stop watching changes if the component is destroyed.
This code uses stopWatch
to avoid memory leaks.
- [Vuejs]-Vue.js SPA redirecting to index.html with .htaccess does not work for every Page
- [Vuejs]-How to prevent normal cursor behavior when pressing keys in a textarea
0👍
Add a ref="helloWorldRef"
to the component then helloWorldRef.value?.$el
it the same as document.querySelector(".hello-world")
. You can get .children
, .clientWidth
, … the same as the querySelector
.
Note that the optional chaining is necessary because it can be null
if not mounted yet. You’d have to implement something to be sure it is available and assigned.
E.g.
watch(
() => helloWorldRef.value?.$el,
(n) => console.log(n)
);
Source:stackexchange.com