[Vuejs]-How do I get the rendered HTML of a component?

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) — calls fn every time the value of ref changes. Returns the function (stopWatch) that watch call will terminate.
  • { immediate: true } — says to run the passed function immediately, in case ref 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.

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)
);

Leave a comment