【问题标题】:Polymer: how to change a parent's property from a child?聚合物:如何从孩子改变父母的财产?
【发布时间】:2017-01-11 11:37:24
【问题描述】:

我有一个非常简单的设置,其中一个父组件有一堆子组件。父组件有一个 pageTitle 属性,我想从正在显示的任何子组件更新它。

所以基本上我有一个带有页面标题的标题,我想根据正在显示的组件进行更新。

这里是父组件:

<dom-module id="my-parent">

  <template>

      <h1>Page title: {{pageTitle}}</h1>

      <a on-tap="changePage" data-page="1">Go to page 1</a><br />
      <a on-tap="changePage" data-page="2">Go to Page 2</a>

      <iron-pages selected="[[page]]" attr-for-selected="data-page>
        <my-child1 data-page="1" page-title="{{pageTitle}}"></my-child1>
        <my-child2 data-page="2" page-title="{{pageTitle}}"></my-child2>
      </iron-pages>
  </template>

  <script>
    Polymer({
      is: 'my-parent',
      properties: {
        page: {type: String, value: "1"},
        pageTitle: {type: String},
      },
      changePage: function(e) {
        var elm = e.currentTarget;
        this.page = elm.getAttribute("data-page");
      }
    });
  </script>

</dom-module>

这是一个孩子的例子:

<dom-module id="my-child1">

  <template>
      <p>We are on page 1</p>
  </template>

  <script>
    Polymer({
      is: 'my-child1',
      properties: {
        pageTitle: {type: String, notify: true, value="Page 1"},
      }
    });
  </script>

</dom-module>

那么现在,我该如何实现:“显示 my-child1 时,更新父级的 pageTitle 属性”?

【问题讨论】:

    标签: data-binding polymer


    【解决方案1】:

    啊,我找到了解决方案。我必须使用 attributeChanged 事件,并根据“iron-selected”检查类名。

    这是使它工作的子组件:

    <dom-module id="my-child1">
    
      <template>
          <p>We are on page 1</p>
      </template>
    
      <script>
        Polymer({
          is: 'my-child1',
          properties: {
            pageTitle: {type: String, notify: true},
          },
          attributeChanged: function(name, type) {
            if (name == "class" && this.getAttribute(name) == "iron-selected") {
              this.set("pageTitle", "Page 1");
            }
          },
        });
      </script>
    
    </dom-module>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      相关资源
      最近更新 更多