从 Vue 组件访问阴影 DOM

Access shadow DOM from Vue Component

我目前正在使用 Vue3 开发自定义组件。我这样定义它:

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

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

现在我正在尝试访问 shadowRoot 以使某些滚动到底部的功能起作用。

我如何访问元素以从 Like 调用 shadowRoot:element.shadowRoot;

我在 vue 文档中找不到任何内容。

在 Vue 组件中,shadow root 是父节点,因此您可以通过 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 })
  }
}

或者您可以查询自定义元素的文档,并直接从引用中访问 shadowRoot 属性。以下示例假设自定义元素在查询时存在于光照 DOM 中,而不存在于阴影 DOM 中。 document.querySelector() 不会穿透阴影 DOM,因此如果该元素位于另一个带有 closed-mode shadow root 的自定义元素内,查询将 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