3

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.

tony19
  • 125,647
  • 18
  • 229
  • 307

1 Answers1

4

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

tony19
  • 125,647
  • 18
  • 229
  • 307
  • If I use it in my main.js like you mentioned, it's getting me `undefined`. The first way with the mounted hook works, tho. Is there a way to also get this inside the composition API with setup? –  Sep 07 '21 at 05:42
  • 1
    The `main.js` example assumes `hello-world` exists in the document at the time of the query. If it's `undefined` for you, that means the element is either not in the document, or is in the shadow DOM (e.g., contained in another custom element). – tony19 Sep 07 '21 at 18:16
  • 2
    Within the Composition API, you can access the component's root element by applying a template ref on the root element. – tony19 Sep 07 '21 at 18:24