Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access shadow DOM from Vue Component

I'm currently working on a custom component with Vue3. I defined it like:

import { defineCustomElement } from 'vue';
import Panel from '~/components/panel_custom/Panel.ce.vue';

const CustomElement = defineCustomElement(Panel);
window.customElements.define('panel-custom', CustomElement);

Now I'm trying to access the shadowRoot to get some scroll-to-bottom function working.

How would I get access to the element to call the shadowRoot from Like: element.shadowRoot;?

I don't find anything in the vue documentation.


1 Answers

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

like image 121
tony19 Avatar answered Dec 07 '25 17:12

tony19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!