[英]Dynamically append child element on load in Polymer 2.0
I'm trying to upgrade to Polymer 2.0 and I can't seem to append child elements on a parent element's load like I could in 1.X. 我正在尝试升级到Polymer 2.0,我似乎无法像在1.X中一样在父元素的负载上追加子元素。 Previously, I think I just used the
ready
callback, but it seems all the callbacks have changed. 以前,我认为我刚刚使用了
ready
回调,但似乎所有的回调都发生了变化。
Seen here in the Callback contracts have changed section. 在Callback合同中看到这里 改变了部分。
I've tried running 我试过跑步
document.getElementById("parent-element").appendChild(document.createElement("child-element"));
on ready
and attached
, yet it seems to be executing the line before parent-element
is even created. ready
并attached
,但它似乎是在创建parent-element
之前执行该行。 This causes an exception: 这会导致异常:
TypeError: Cannot read property 'appendChild' of null
I've also tried using 我也试过用
this.$.container.appendChild(document.createElement("child-element"));
where container
is the id
of an empty <div>
inside the parent element, but I get the same issue. 其中
container
是父元素中空<div>
的id
,但我遇到了同样的问题。 I'm pretty new to Polymer, so if there's a better method or structure I can use to get what I need, let me know. 我是Polymer的新手,所以如果有更好的方法或结构我可以用来获得我需要的东西,请告诉我。
From the 1.x -> 2.x upgrade guide : 从1.x - > 2.x 升级指南 :
- For standard DOM operations, remove the Polymer.dom() wrapper.
对于标准DOM操作,请删除Polymer.dom()包装器。
- Use this.shadowRoot in place of Polymer.dom(this.root).
使用this.shadowRoot代替Polymer.dom(this.root)。
The ready()
callback is now asynchronous (microtask) due to the webcomponents v1 spec. 由于webcomponents v1 spec,
ready()
回调现在是异步的(微任务)。 To mitigate this, use settimeout
, which is another task at the browser level and runs after microtasks. 要缓解这种情况,请使用
settimeout
,这是浏览器级别的另一项任务,并在微任务之后运行。 Source of next code block . 下一个代码块的来源 。
ready() {
super.ready();
setTimeout(function() {
var distributedNodes = this.$.slot.assignedNodes({flatten: true});
console.log(distributedNodes);
}.bind(this), 0);
}
If you want to dig into tasks and microtasks this blog post is a great read . 如果你想深入研究任务和微任务, 这篇博文是一篇很好的阅读 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.