在下面的示例中,我尝试创建一个菜单组件来试验组件层次结构。
索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="robots" content="index, follow">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Sample Menu App</title>
<script src="js/webcomponents-lite.js"></script>
<!-- Components -->
<link rel="import" href="components/global/site-navigation.html">
</head>
<body>
<site-navigation></site-navigation>
</body>
</html>
/components/global/site-navigation.html
<link rel="import" href="nav-item.html">
<template>
<div class="nav">Header Goes here</div>
<ul class="nav">
<nav-item>Item 1</nav-item> <!-- This is a child component-->
</ul>
</template>
<script>
(function (currentDocument) {
customElements.define('site-navigation', class SiteNavigation extends HTMLElement {
constructor() {
super();
const shadowTemplate = currentDocument.querySelector('template').content.cloneNode(true);
this.DOM = this.attachShadow({ mode: 'open' });
this.DOM.appendChild(shadowTemplate);
console.log(this.DOM);
}
connectedCallback(){
this.Initialize();
}
Initialize(){
this.DOM.querySelector("div.nav").innerHTML = "Title"
}
});
})((document.currentScript || document._currentScript).ownerDocument);
</script>
/components/global/nav-item.html
<template>
<li class="nitem">
<a href="#">Elements</a>
</li>
</template>
<script>
(function(currentDocument) {
customElements.define('nav-item', class SiteNavigationItem extends HTMLElement {
constructor() {
super();
const shadowTemplate = currentDocument.querySelector('template').content.cloneNode(true);
this.DOM = this.attachShadow({ mode: 'open' });
this.DOM.appendChild(shadowTemplate);
}
connectedCallback(){
this.Initialize();
}
Initialize(){
let aTag = this.DOM.querySelector('a');
aTag.innerHTML = "Link 1"
}
});
})((document._currentScript||document.currentScript).ownerDocument);
</script>
它在 Chrome 中运行良好。我已经应用了 Polyfill以使其在其他浏览器中工作。但是,Initialize 方法在 FireFox 中失败,并显示消息TypeError: this.DOM.querySelector(...) is null。调试发现this.DOM = this.attachShadow({ mode: 'open' });
FF和Chrome返回的对象类型不同,FF结果中没有querySelector!我该如何解决这个问题?
更新: 如果删除了对子组件(导航项)的链接/引用,则父组件(站点导航)工作正常。