聚合物:无法从主机传入 this.__data__

Polymer: can't get this.__data__ passing in from host

我有一个非常简单的项目:

app/
    parent.html
    child.html
index.html

我尝试将数据从父级传递给子级,然后在 Polymer() 中获取它们:

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>

app/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>

app/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>

问题在于,只有当从主机传输的数据像上面那样在模板开启器标记旁边隐式声明时,Polymer 才会看到 this.__data__。如果我从那里删除它,它就看不到它。所以它看起来像一个把戏。我不想将该数据放在模板中,我想在 Polymer 函数中使用它。但我不知道如何正确地实现这一点,没有任何技巧的正确方法是什么。 相信有人知道。

您可以通过 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;
  }
});

在属性对象中配置策略而不是在父对象中配置就绪周期,并根据父属性名称在子对象中创建属性,在下面的代码中提到

Parent.html

聚合物({ 是:"x-comphost",

  properties :{

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

  }
});

Child.html

聚合物({ 是:"x-child"、

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

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