I've been experimenting with web components using Vue3 and I'm curious about how the Shadow DOM works. I encountered an issue where a third party library was trying to access elements using getElementById() and it was throwing an error because the element was null. It seems that this is due to the restricted access from the web component to the actual DOM, making it difficult for functions to locate HTML elements used within the component itself. Can someone shed light on why this limitation exists? And how can I properly access these elements? Would using shadowRoot help?
Test.vue
:
<template>
<div id="test">Hello World!</div>
</template>
<script lang="js">
import {
ref,
onMounted
} from "vue";
export default {
setup(props) {
onMounted(() => {
// NULL
console.log(document.getElementById("test"));
});
}
}
</script>
main.js
:
import { defineCustomElement } from 'vue'
import Test from './Test.vue'
const ExampleElement = defineCustomElement(Test)
// register
window.customElements.define('test-component', ExampleElement)