在递归聚合物组件中插入新子组件时,无法读取未定义的属性“concat”

Cannot read property ‘concat’ of undefined when inserting new child into recursive Polymer component

本文关键字:组件 未定义 读取 concat 属性 聚合物 递归 插入      更新时间:2023-09-26

我遇到了递归聚合物组件的麻烦,该组件有一个用于插入新元素的按钮。它有add链接用于插入元素。当单击我最初定义的元素时,它们可以工作,但对于由add插入的元素则失败-我得到一个错误Cannot read property ‘concat’ of undefined

触发错误,单击add链接,插入节点成功,然后在插入节点上再次单击add。这将失败并显示错误。

<script src="https://www.polymer-project.org/1.0/components/webcomponentsjs/webcomponents.min.js?20150925"></script>
<link rel="import" href="https://rawgit.com/Polymer/polymer/4c94736fac6681e84ec8c00da53484c5d3c2226b/polymer.html">
<template is="dom-bind">
  <test-insert></test-insert>
</template>
 
<dom-module id="test-insert">
  <template>
    <test-recurse object="[[_object]]"></test-recurse>
  </template>
</dom-module>
<dom-module id="test-recurse">
  <template>
    <style>
      a { color: blue; text-decoration: underline; cursor: pointer; padding-left: 1em;}
    </style>
    Label: <span>[[object.label]]</span>   <a on-click="_pushNewElement">add</a>
    <ul>
      <template is="dom-repeat" items="[[object.children]]">
        <li><test-recurse object="[[item]]"></test-recurse></li>
      </template>
    </ul>
  </template>
</dom-module>
<script>
(function () {
  Polymer({
    is: 'test-insert',
    properties: {
      _object: Object
    },
    ready: function () {
      this._object = {
        label: 'a1', 
        children: [
          { label: 'b1', children: [] }, 
          { label: 'b2', children: [{label: 'c1', children: []}] }
        ]
      };
    }
  });
  var count = 0;
  Polymer({
    is: 'test-recurse',
    properties: {
      object: Object
    },
    _pushNewElement: function () {
      var newLabel = {label: 'Object ' + (++count)};
      console.log({newLabel: newLabel}, '_pushNewElement');
      this.object.children = this.object.children || [];
      this.unshift('object.children', newLabel);
    }
  });
}());
</script>

任何帮助都非常感谢!

你只需要修改一行:

this.set('object.children', this.object.children || []);

children数组未正确创建