2016-09-13 45 views
0

中走過時,我有一個非常簡單的項目:聚合物:不能得到這個.__ data__從主機

app/ 
    parent.html 
    child.html 
index.html 

我嘗試從母公司中聚合物()將數據傳遞給孩子,然後讓他們:

的index.html

<!DOCTYPE html> 
<html> 
    <head> 
    <link rel="import" href="bower_components/polymer/polymer.html"> 
    <link rel="import" href="app/parent.html"/> 
    </head> 
    <body> 
    <h1>Hello Paul!</h1> 
    <x-comphost></x-comphost> 
    </body> 
</html> 

應用程序/ parent.html

<link rel="import" href="child.html"/> 
<dom-module id="x-comphost" noscript> 
    <template> 
    <h4>Hello, man!</h4> 
    <p>I'm seeking a child</p> 
    <x-child accessible-policies="{{policies}}"></x-child> 
    </template> 
    <script> 
    Polymer({ 
     is: "x-comphost", 
     ready: function(){ 
     this.policies = ['Hospital', 'Dental', 'Travel']; 
     } 
    }); 
    </script> 
</dom-module> 

應用程序/ child.html

<dom-module id="x-child" noscript> 
    <template> 
     [[accessiblePolicies]] 
     <h5>Hello again!</h5> 
     <p>Remember me?</p> 
    </template> 
    <script> 
     Polymer({ 
      is: "x-child", 
      properties: {}, 
      ready: function() { 
       console.log('thisData', this.__data__); 
      } 
     }); 
    </script> 
</dom-module> 

麻煩的是,聚合物僅看到如果從主機被髮送數據this.__data__被隱式地像上述所聲明,毗鄰模板開罐器標籤。如果我從那裏刪除它不能看到它。所以它看起來像一個伎倆。我不想將這些數據放在模板中,我想在Polymer函數中使用它。但我不知道如何正確實現這一點,沒有任何竅門的正確方法是什麼。 我相信有人知道。

回答

1

您可以通過JavaScript接口傳遞數據,只需添加以下到父(x-comphost)實現:

Polymer({ 
    is: "x-comphost", 
    ready: function(){ 
    this.policies = ['Hospital', 'Dental', 'Travel']; 

    /* Query shadow DOM for the x-child element */ 
    var childEl = Polymer.dom(this.root).querySelector('x-child'); 

    childEl.accessiblePolicies = this.policies; 
    } 
}); 
+0

嗯,我有數據,但不是這裏面.__ data__我推測,但像this.accessiblePolicies。然而,爲了理解一切,需要一些時間。 – srgg6701

+0

順便說一句,它甚至可能不傳遞數據,而是使用this.domHost代替孩子。 – srgg6701

+1

雖然它的工作原理我建議不要使用這個,直到必要爲止,因爲這基本上是穿透陰影 - dom,由於性能原因在所有瀏覽器中無法使用Shadow-dom V0,故意由Polymer保留打開的漏洞。但是,在所有主流瀏覽器中幾乎都實現了Shadow-dom V1並且接近發佈的Polymer 2.0將被棄用。你可以閱讀[這裏](https://www.polymer-project.org/1.0/blog/2016-09-09-polymer-2.0) – a1626

0

在性能配置策略,而不是反對準備週期在父母按父屬性名化妝在子屬性,下面的代碼

Parent.html

聚合物({ 是提到: 「X-comphost」,

properties :{ 

    policies : { 
     type : Array, 
     value : ['Hospital', 'Dental', 'Travel'] 
    } 
    }, 
    ready: function(){ 
    // this.policies = ['Hospital', 'Dental', 'Travel']; 

    } 
}); 

Child.html

聚合物({ 是: 「X-子」,

 properties: { 
      accessiblePolicies : { 
       type : Array, 
       value : []    } 

     }, 
     ready: function() { 
      console.log('thisData', this.accessiblePolicies); 
     } 
    });