第一个组成部分:x-input。一个非常简单的输入组件:
(function() {
class XInput extends HTMLElement {
static get template() {
const template = document.createElement('template');
template.innerHTML = `
<style>
:host {
display: block;
}
</style>
<input id="input">
`;
return template;
}
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(XInput.template.content.cloneNode(true));
}
}
window.customElements.define('x-input', XInput);
})();
我的组件位于.js文件中,因此我不需要在客户端页面中使用HTML Import。 现在,我需要一个继承x-input的第二个Web组件:
(function() {
class XInputNumber extends XInput {
}
window.customElements.define('x-input-number', XInputNumber);
})();
如果我尝试在页面中使用第二个元素 - &gt;未捕获的ReferenceError:未定义XInput。
<html>
<head>
<script src="/bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<script src="/bower_components/shadydom/shadydom.min.js"></script>
<script src="/webcomponents/input/x-input.js"></script>
<script src="/webcomponents/input/x-input-number.js"></script>
</head>
<body>
<p><x-input></x-input></p>
<p><x-input-number></x-input-number></p>
</body>
</html>
如果我在html文件中编写我的Web组件,没问题,但我必须使用HTML Imports(我试着没有它)。
我怎样才能做到这一点?
答案 0 :(得分:2)
正如您所注意到的,XInput类仅在闭包中定义。如果您想在其他地方重复使用它,您可以在全局范围内定义它,或者在customElements.get()
方法的帮助下对其进行检索。
在 x-input-number.js 文件中:
(function() {
var XInput = customeElements.get('x-input');
class XInputNumber extends XInput {
}
window.customElements.define('x-input-number', XInputNumber);
})();
或直接:
class XInputNumber extends customeElements.get('x-input') {}