在 Polymer 2.0 中加载时动态附加子元素
Dynamically append child element on load in Polymer 2.0
我正在尝试升级到 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
是父元素内空 <div>
的 id
,但我遇到了同样的问题。我是 Polymer 的新手,所以如果有更好的方法或结构可以用来获得我需要的东西,请告诉我。
来自 1.x -> 2.x upgrade guide:
- For standard DOM operations, remove the Polymer.dom() wrapper.
- Use this.shadowRoot in place of Polymer.dom(this.root).
由于 webcomponents v1 规范,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。
我正在尝试升级到 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
是父元素内空 <div>
的 id
,但我遇到了同样的问题。我是 Polymer 的新手,所以如果有更好的方法或结构可以用来获得我需要的东西,请告诉我。
来自 1.x -> 2.x upgrade guide:
- For standard DOM operations, remove the Polymer.dom() wrapper.
- Use this.shadowRoot in place of Polymer.dom(this.root).
由于 webcomponents v1 规范,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。