我有一个 Shadow 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 Custom 元素也必须是您的 ShadowRoot。希望这适合您的需求。
https://github.com/karol-f/vue-custom-element 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 的代码。您可以这样做并创建拉取请求,或者自己修改它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)