When it comes to calling a function that requires an HTMLElement
as an argument, the element in question is rendered within my page template and therefore I need to ensure it is actually in the DOM before making the call. Two potential methods for waiting for the element to be visible are:
- Utilizing a
ref
<template><div ref="el"></div></template>
<script>
import {ref, watch} from "vue";
import {exampleFunction} from "example";
export default {
setup() {
const el = ref();
watch(el, (newEl, oldEl) => {
if (typeof oldEl === "undefined") // Ensure function is called only once
exampleFunction(newEl);
});
return {el}
}
}
</script>
- Using
onMounted
<template><div id="el" ref="el1"></div></template>
<script>
import {onMounted, ref} from "vue";
import {exampleFunction} from "example";
export default {
setup() {
const el1 = ref();
onMounted(() => {
let el2 = document.querySelector("#el");
exampleFunction(el2);
// OR exampleFunction(el1.value);
});
return {el1}
}
}
</script>
In my understanding, both of these approaches provide a reference to the element once it is present in the DOM. Is there any particular reason why one method might be preferred over the other? Are there any nuances about either of these scenarios that I may have overlooked? Lastly, could there be another solution entirely that would be more suitable for this situation?