javascript - 如何让 Vue 在 shadow dom 中工作

标签 javascript html vue.js

我有一个影子 dom,其中包含根元素和一个 vue 组件。

<template>
    <div class="container">
        <div id="app"></div>
    </div>
    <script src="http://my-site.com/app/js/vue-component.js"></script>
</template>

<div id="hostElement"></div>
<script>
// create shadow DOM on the <p> element above
const shadow = document.querySelector('#hostElement').attachShadow({mode: 'open'});
const template = document.querySelector('template');
shadow.appendChild(document.importNode(template.content, true));
</script>

vue-component.js 内部看起来像这样:

import Vue from 'vue';

const shadow = document.querySelector('#hostElement').shadowRoot;

new Vue({
    el: shadow.querySelector('#app'),
    // ...
})

// this doesn't work because I think Vue is using document.querySelector('#app')
// instead of the required document.querySelector('#hostElement').shadowRoot.querySelector('#app')
// new Vue ({
//     el: '#app'
// })

如果我在 shadow dom 之外使用这些东西(就像普通人那样),一切都很好。然而,Vue 似乎无法处理 shadow dom 的东西。我相信它不应该调用 document.querySelector 如果它在 shadow dom 中。相反,它应该运行 shadowRoot.querySelector

如果这让我感到困惑,请告诉我,我处在一个不常见的用例场景中,所以有点难以解释。

最佳答案

---更新---

如果您传递对元素的引用而不是选择器,Vue 将使用该元素。

let element = document.querySelector('#host-element').shadowRoot.querySelector('#your-future-vue-component');
new Vue({
  el: element,
  ...
})

---旧东西---

我使用 vue-custom-element 为您提供了一半的解决方案。我说一半,因为它将你的 vue 组件放入一个 web 组件中,并让你可以选择让它使用影子 DOM。这意味着 Vue 自定义元素也必须是您的 shadowRoot。希望这能满足您的需求。

https://github.com/karol-f/vue-custom-element

import Vue from 'vue';
import vueCustomElement from 'vue-custom-element';
import app from './app.vue';

Vue.use(vueCustomElement);
Vue.customElement("my-element", app, {shadow: true});
myShadowElement = document.createElement('my-element');
document.body.appendChild(myShadowElement);

我认为您唯一的其他选择是去修改 Vue 的代码。您可以这样做并创建一个拉取请求,或者自己破解它。

关于javascript - 如何让 Vue 在 shadow dom 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46879782/

相关文章:

javascript - 在触摸设备上捕获并停止拖动

javascript - 获取数组 VueJS 的最后一项

javascript - NuxtJS:在生产环境中禁用 console.log

javascript - JS : Bug converting string to Date

javascript - 按顺序加入两个数组的成员

html - 全局类 CSS 中的文本阴影覆盖

html - 隐藏在父边框后面的 Css div 溢出

html - 为什么第一行未对齐?

javascript - 在子组件Vue Js中使用父组件数据

javascript - 使用 javascript 从给定字符串获取电子邮件 ID