Best way to pass/receive data to/from other sibling components?

拜拜、爱过 提交于 2020-06-23 15:57:11

问题


Recently I am trying to learn web components/custom elements and I have came across with a problem and that is pass/receive data to/from other sibling components, I have tried using custom event to do the data passing and receiving but sometimes in some situations, custom event is not really the best way to do it, so what my question is other than custom events, is there any other ways I can pass/receive data to/from other sibling components?

index.html

<body>
  <my-component-one></my-component-one>
  <my-component-two></my-component-two>

  <script src="./my-component-one.js"></script>
  <script src="./my-component-two.js"></script>
</body>

Another way I can think of doing the data passing and receiving is using the document(not the custom element's #document-fragment) to get the custom element and pass or read the data to/from the custom element's property but I am not sure if this is the best solution...

something like this?

my-component-one.js

...

connectedCallback(){

  const myComponentTwo = document.querySelector('my-component-two');
  myComponentTwo.myData = {
    data: 'My data!'
  }

}

...

and I am not using any kinds of web components libraries.

来源:https://stackoverflow.com/questions/62373477/best-way-to-pass-receive-data-to-from-other-sibling-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!