-->

Linking 2 custom elements through parent

2019-08-27 04:53发布

问题:

I have 2 custom child elements that I am trying to pass data between through a parent element. My code in the parent html looks something like this:

<dom-module id="parent-html">
 <template>
  <child-elem1 id="ch1"></child-elem1>
  <child-elem2 id="ch2"></child-elem2>
 </template

<script>
window.addEventListener('WebComponentsReady', function() {
  class WebApp extends Polymer.Element {
    static get is() { return 'web-app'; }
    static get properties() {
      return {
      }
    }
    ready () {
      super.ready();
      this.$.ch1.datamodel = this.$.ch2;
    }
  }
  window.customElements.define(WebApp.is, WebApp);
  });
</script>
</dom-module>

As you can see I am trying to use the ready function in the parent html to link an object in the first child element called datamodel with the second child element. This would then allow me to pass data from child-elem2 into the property of datamodel in child-elem1.

I know the data is able to reach this parent html but this link does not work as I am not getting the data in child-elem1.

What is the best way of doing this? TIA

Update: When I test what is in [[datamodel]] within child-elem1 it displays [object HTMLElement] so it seems like it is able to see the other child html but as of now there is still no data being passed in.

回答1:

Passing an Object from one child element to another is one of the easy approaches at Polymer. Please refer for more information :

  <child-elem1 id="ch1" datamodel="{{datamodel}}" ></child-elem1>
  <child-elem2 id="ch2" datamodel="{{datamodel}}" ></child-elem2>

at child-elem2:

 ....
 <div>At child Element -2 : [[datamodel.name]]</div>
 ....
 class ChildElem2 extends Polymer.Element {
      static get is() { return 'child-elem2'; }
      static get properties() { return { 
        datamodel: {
            type:Object,
            notify:true
        }
     }};
    static get observers() { return []}

      ready() {
            super.ready();
            setTimeout(()=>{
                this.set('datamodel.name', 'John Doe') //our famous developer Hero :) 
            },900)
        }


 }
customElements.define(ChildElem2.is, ChildElem2);
 });

DEMO ( A similar one)