下面是一个带有两个本机V1 Web组件的示例应用程序。
<component-1>
可以与对话
<component-2>
因为你提供了一个ID到
<组件1>
该ID指的是设置在
<组件2>
.
这与
<label>
使用its标记工作
for
HTML
<component-1 link-id="c2"></component-1>
<hr/>
<component-2 id="c2"></component-2>
JS公司
// Class for `<component-1>`
class Component1 extends HTMLElement {
constructor() {
super();
this._linkedComponent = null;
this._input = document.createElement('input');
this._input.addEventListener('focus', this._focusHandler.bind(this));
this._button = document.createElement('button');
this._button.textContent = 'Add';
this._button.addEventListener('click', this._clickHandler.bind(this));
}
connectedCallback() {
this.appendChild(this._input);
this.appendChild(this._button);
}
static get observedAttributes() {
return ['link-id'];
}
attributeChangedCallback(attrName, oldVal, newVal) {
if (oldVal !== newVal) {
if (newVal === null) {
this._linkedComponent = null;
}
else {
this._linkedComponent = document.getElementById(newVal);
}
}
}
_clickHandler() {
if (this._linkedComponent) {
this._linkedComponent.value = this._input.value;
}
}
_focusHandler() {
this._input.value = '';
}
}
// Class for `<component-2>`
class Component2 extends HTMLElement {
constructor() {
super();
this._textArea = document.createElement('textarea');
this._textArea.setAttribute('style','width:100%;height:200px;');
}
connectedCallback() {
this.appendChild(this._textArea);
}
set value(newValue) {
this._textArea.value += (newValue+'\n');
}
}
customElements.define('component-1', Component1);
customElements.define('component-2', Component2);
<组件1>
只会与
<组件2>
如果有一个ID为的组件提供给
<组件1>
通过its
link-id
属性