【问题标题】:Access shadow DOM from Vue Component从 Vue 组件访问 shadow DOM
【发布时间】:2021-11-03 10:00:27
【问题描述】:

我目前正在使用 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:element.shadowRoot; 调用 shadowRoot?

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

【问题讨论】:

    标签: vue.js vuejs3 shadow-dom custom-component


    【解决方案1】:

    在 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 属性。下面的示例假设在查询时自定义元素存在于 light DOM 中,而不是 shadow DOM 中。 document.querySelector() 不会穿透 shadow DOM,因此如果该元素位于另一个带有 closed-mode shadow root 的自定义元素中,则查询将返回 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

    【讨论】:

    • 如果我像你提到的那样在我的 main.js 中使用它,它会让我undefined。安装挂钩的第一种方式有效。有没有办法通过设置在组合 API 中也得到这个?
    • main.js 示例假定hello-world 在查询时存在于文档中。如果它是undefined,则意味着该元素不在文档中,或者在影子 DOM 中(例如,包含在另一个自定义元素中)。
    • 在 Composition API 中,您可以通过在根元素上应用模板引用来访问组件的根元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 2021-01-04
    • 2015-05-08
    • 2018-06-25
    • 2014-07-18
    • 1970-01-01
    相关资源
    最近更新 更多