通过父级链接2个自定义元素 [英] Linking 2 custom elements through parent

查看:67
本文介绍了通过父级链接2个自定义元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个自定义子元素,我试图通过一个父元素在两个子元素之间传递数据.我在父html中的代码如下所示:

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>

如您所见,我正在尝试使用父html中的ready函数将名为datamodel的第一个子元素中的对象与第二个子元素链接.然后,这将允许我将数据从child-elem2传递到child-elem1中的datamodel属性.

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.

我知道数据能够到达此父html,但是此链接不起作用,因为我没有在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.

做到这一点的最佳方法是什么? TIA

What is the best way of doing this? TIA

更新:当我测试child-elem1的[[datamodel]]中的内容时,它会显示[object HTMLElement],因此似乎可以看到其他子html,但是到目前为止,仍然没有数据通过内.

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.

推荐答案

将对象从一个子元素传递到另一个子元素是Polymer的一种简便方法.请参阅更多信息:

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>

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);
 });

演示(类似)

这篇关于通过父级链接2个自定义元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆