我正在尝试升级到Polymer 2.0,我似乎无法像在1.X中一样在父元素的负载上追加子元素。以前,我认为我刚刚使用了ready
回调,但似乎所有的回调都发生了变化。
在回调合约已更改部分中看到here。
我试过了
document.getElementById("parent-element").appendChild(document.createElement("child-element"));
在ready
和attached
上,但似乎在parent-element
创建之前执行了该行。这会导致异常:
TypeError: Cannot read property 'appendChild' of null
我也尝试过使用
this.$.container.appendChild(document.createElement("child-element"));
其中container
是父元素中空id
的{{1}},但我遇到了同样的问题。我是Polymer的新手,所以如果有更好的方法或结构我可以用来得到我需要的东西,请告诉我。
答案 0 :(得分:2)
来自1.x - > 2.x upgrade guide:
- 对于标准DOM操作,请删除Polymer.dom()包装器。
- 使用this.shadowRoot代替Polymer.dom(this.root)。
由于webcomponents v1 spec,ready()
回调现在是异步的(微任务)。要缓解这种情况,请使用settimeout
,这是浏览器级别的另一项任务,并在微任务之后运行。 Source of next code block
ready() {
super.ready();
setTimeout(function() {
var distributedNodes = this.$.slot.assignedNodes({flatten: true});
console.log(distributedNodes);
}.bind(this), 0);
}
如果你想挖掘任务和微任务this blog post is a great read。