1

I created a custom-component cause I needed to scope the css.

import { defineCustomElement } from "vue";
…
const CustomElement = defineCustomElement(ImportConfig);
window.customElements.define("import-new-custom", CustomElement);

How would I access elements with JS, to change styles dynamically, inside custom-components using vues composition api? I tried utilizing template refs but that doesn't fit all needs.

Appreciate all help. Didn't find any up to date information for Vue.

temp
  • 519
  • 7
  • 18
  • A custom element is almost the same as any other Vue component - the only difference is that you can directly use it in 3rd party HTML without the need of Vue-template-compiler to preprocess it. – IVO GELOV Aug 09 '22 at 11:41
  • And still it's using the shadow dom to isolate itself and I can't get elements using e.g. `getElementById`. – temp Aug 09 '22 at 11:46
  • If you want to access the DOM nodes inside your Shadow Root - you must use the `open` mode of Shadow DOM. Open vs closed modes are explained in https://blog.revillweb.com/open-vs-closed-shadow-dom-9f3d7427d1af – IVO GELOV Aug 09 '22 at 11:49
  • If it has an ``open`` shadowRoot, it is ``document.querySelector("import-new-custom").shadowRoot.getElementById(..)`` – Danny '365CSI' Engelman Aug 09 '22 at 11:49
  • @Danny'365CSI'Engelman Thaks! That helped me a lot. Just couldn't figure out how to access the parents shadowRoot. If you could write this as an answer I'd accept it. – temp Aug 09 '22 at 11:52

1 Answers1

1

If it is an open shadowRoot, it is document.querySelector("import-new-custom").shadowRoot.getElementById(..). A closed shadowRoot does not have a .shadowRoot property. But you (the Component Developer) can assign an entrypoint yourself.

For a recursive dive into shadowRoots; see: How to reference to a method in parent component from child component with vanilla JS Web Components? (Not any framework or Library)

From inside a shadowRoot you get the host element with: this.getRootNode().host

standard .closest(...) does not cross shadowRoot boundaries; for a closestElement(..) see: How to reference to a method in parent component from child component with vanilla JS Web Components? (Not any framework or Library)

Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49