From within the Vue component, the shadow root is the parent node, so you could access it via this.$el.parentNode
:
export default {
mounted() {
// assuming this Vue component is mounted as a custom element
// via `defineCustomElement()` and `window.customElements.define()`
console.log({ shadowRoot: this.$el.parentNode })
}
}
Or you can query the document for the custom element, and access the shadowRoot
property directly from the reference. The following example assumes the custom element exists in the light DOM at the time of query, and not within the shadow DOM. document.querySelector()
does not pierce the shadow DOM, so if the element is within another custom element with a closed-mode shadow root, the query will return undefined
.
import { defineCustomElement } from 'vue'
import HelloWorld from '@/components/HelloWorld.vue'
const CustomElement = defineCustomElement(HelloWorld)
window.customElements.define('hello-world', CustomElement)
// assume element is in light DOM
const el = document.querySelector('hello-world')
console.log({ shadowRoot: el?.shadowRoot })
demo