如何从子元素更改父元素 属性?

How to change parent element property from child element?

如何让子元素更改父元素中 属性 的值,并能够观察到父元素中的更改

<link rel="import" href="paper-tree-node.html">

<dom-module id="paper-tree">
  <template>
    <div>
      <paper-tree-node id="root" data="[[data]]" actions="[[actions]]" on-click='_handlePaperCheck' chapterIds={{chapterIds}}></paper-tree-node>
    </div>
  </template>
</dom-module>

<script>
  Polymer({

    is: 'paper-tree',

    properties: {
      chapterIds: {
        type: Array,
        value: [],
        notify: true,
        observer: "_chapterChanged"

      }
    },
    _handlePaperCheck: function (e) {
      let element = e.target.parentElement
      if (element.checked) {
        this.push('chapterIds', parseInt(element.id.substr(2)))
        // console.info(this.chapterIds);


      } else {
        var index = this.chapterIds.indexOf(element.id);

        this.splice('chapterIds', index, 1)
        // console.info(this.chapterIds);

      }

    },
    _chapterChanged: function () {
      console.log(this.chapterIds)
      //   this.$.root.chapterIds = this.chapterIds
    }
  })

注意到 paper-tree-node 是一个子元素,在其模板中包含一个 paper-check,这样做的目的是获取被点击的 paper-tree-node id 属性并将其推送到 chapterIds 属性.

问题是当我点击任何复选框时 _chapterChanged 不会触发

我附上了一个示例项目,因为它不能发布在 jsbin 之类的东西上,这里是项目的 gdrive zip 文件夹 https://drive.google.com/file/d/1yCeXkZu8Yp-8GUgadGHIfeP5w5uyI12J/view?usp=sharing

您可以使用 event or with data 绑定来做到这一点。

您的想法是正确的,但不是全部。

notify: true, 应该在 属性 chapterIds 下的子元素 paper-tree-node 中声明,而不是在 paper-tree 元素下。我在开始使用 Polymer 时也犯了这个错误。

此外,每当 Polymer 看到驼峰式变量时,它都会假定该变量包含破折号:

  <paper-tree-node id="root" data="[[data]]" actions="[[actions]]" on-click='_handlePaperCheck' chapterIds={{chapterIds}}></paper-tree-node>

...应该是...

  <paper-tree-node id="root" data="[[data]]" actions="[[actions]]" on-click='_handlePaperCheck' chapter-ids={{chapterIds}}></paper-tree-node>

... 我将 属性 chapterIds 切换为 chapter-ids。我在创建新元素时很少使用驼峰式变量,因为这个错误很容易犯。