我最近正在尝试使用Web组件,但是遇到一个问题,如何将数据从第一个组件发送到第二个组件?
我尝试使用事件,但是第二个组件无法接收数据,这就是我所做的:
(对此我完全陌生,不确定我是否做对了)
Index.html
<body>
<first-component>
<p>First component!</p>
</first-component>
<second-component>
<p>Second component!</p>
</second-component>
<script src="./component-one.js"></script>
<script src="./component-two.js"></script>
</body>
component-one.js
const firstComponentTemplate = document.createElement('template');
firstComponentTemplate.id = 'first-component-template';
firstComponentTemplate.innerHTML = `
<div id="first-component-container">
<slot></slot>
<button>Click</button>
</div>
`;
class FirstComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(firstComponentTemplate.content.cloneNode(true));
}
btnClick() {
const btnHtml = this.shadowRoot.querySelector('button');
btnHtml.addEventListener('click', () => {
this.dispatchEvent(
new CustomEvent('a-custom-event', {
bubbles: true,
composed: true,
detail: {
value: 'Some value',
},
})
);
});
}
connectedCallback() {
this.btnClick();
}
}
customElements.define('first-component', FirstComponent);
component-two.js
const secondComponentTemplate = document.createElement('template');
secondComponentTemplate.id = 'second-component-template';
secondComponentTemplate.innerHTML = `
<div id="second-component-container">
<slot></slot>
</div>
`;
class SecondComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(secondComponentTemplate.content.cloneNode(true));
}
connectedCallback() {
this.shadowRoot.addEventListener('a-custom-event', function (event) {
console.log(event); //Check console but nothing in console
});
}
}
customElements.define('second-component', SecondComponent);
如您所见,我正在尝试将数据从第一个自定义元素传递到第二个自定义元素,
这怎么不起作用,我哪一部分做错了?
这是正确的方法吗?
将数据从一个组件传递/接收到另一个兄弟组件是不好的做法吗?
谢谢