Полимер: добавление тега динамического компонента с привязками - PullRequest
0 голосов
/ 07 марта 2019

Я использую Polymer 2.0 и хочу динамически вставить элемент компонента в DOM, для которого будут установлены правильные привязки.

<child-component collection="[[ parentCollection ]]"></child-component>

В этом примере у компонента child-component есть свойство, называемое коллекцией, это свойство collection должно быть связано со свойством parentCollection родительского компонента (которое является простомассив чисел).

const node = document.createElement('child-component');
node.setAttribute('collection', '[[ parentCollection ]]');
this.$.container.appendChild(node);

Вышеуказанное не работает.Установка его как innerHTML (например, '<child-component collection="[[ parentCollection ]]"></child-component>') также не работает.

Пример родительского компонента

class ParentComponent extends Polymer.Element {
    static get is() { return 'parent-component'; }

    static get properties() {
        return {
           parentCollection: {
               type: Array,
               value: [1,2,3,4,5],
           }
        };
    }
}

customElement.define(ParentComponent.is, ParentComponent);

Пример дочернего компонента

class ChildComponent extends Polymer.Element {
    static get is() { return 'child-component'; }

    static get properties() {
        return {
            collection: {
                type: Array,
                value: [],
            }
        };
    }

    connectedCallback() {
       super.connectedCallback();

       // The desired log would be [1,2,3,4,5]
       console.log(this.collection);
    }
}

customElement.define(ChildComponent.is, ChildComponent);

Образец Dom Module

<dom-module id="parent-component">
    <template>
        <style></style>
        <div id="container></div>
    </template>
    <script src="parent-component.js"></script>
</dom-module>

Я пытался изучить Polymer.Bind и Polymer.PropertyEffects миксин, но, похоже, никуда не могу добратьсяс этим.

Любая помощь будет высоко ценится.Спасибо!

1 Ответ

0 голосов
/ 08 марта 2019

Вот пример из-за вашего желания выше, как создать динамически полимерный элемент и определить значение .:

Демо

 HTMLImports.whenReady(function() {
    
   class ParentComponent extends Polymer.Element {
      static get is() { return 'parent-component'; }
      static get properties() { return { 
         parentCollection: {
               type: Array,
               value() { return  [1,2,3,4,5]; }
           }
      }}
          ready(){
            super.ready();
            let nod = document.createElement('child-component')
            nod.collection = this.parentCollection;
            this.shadowRoot.querySelector('#container').appendChild(nod);
          }
 }
      
 customElements.define(ParentComponent.is, ParentComponent);
    
    class ChildComponent extends Polymer.Element {
      static get is() { return 'child-component'; }
      static get properties() { return { 
                 collection: {
                           type: Array,
                           value() {return [];}
                 }
              }
            }
      
      connectedCallback(){
        super.connectedCallback();
           console.log('this collection from child: ', this.collection)
      }
 }
customElements.define(ChildComponent.is, ChildComponent);
 });
<html>
<head>
<base href="https://cdn.rawgit.com/download/polymer-cdn/2.6.0.2/lib/">
<script src="webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="polymer/polymer.html">
<script src="webcomponentsjs/webcomponents-lite.js"></script>

</head>
 <body> 
  <parent-component></parent-component>
  <dom-module id="parent-component">
  <template>
    <style>
      :host {
        display: block;
        height: 100%;
      }
  </style> 
    <div id="container"></div>
  </template> 
</dom-module>  
</body>
</html>
...