我试图了解使用Shadow DOM如何在Stenciljs中影响组件生命周期方法。
我已经在Stencil入门应用程序中设置了以下示例。
<body>
<my-app>
<component-a>
<component-c />
</component-a>
<component-b />
</my-app>
...
</body>
组件定义为:
@Component({
tag: 'my-app',
styleUrl: 'my-app.css'
})
@Component({
tag: 'component-a'
})
@Component({
tag: 'component-b'
})
@Component({
tag: 'component-c'
})
每个组件在其每个生命周期方法中都有控制台语句。当页面加载到浏览器中而没有任何组件打开影子DOM时。
09:30:00.603 my-app.js:19 my-app is about to be rendered
09:30:00.605 component-a.js:19 component-a is about to be rendered
09:30:00.606 component-c.js:19 component-c is about to be rendered
09:30:00.606 component-c.js:30 component-c has been rendered
09:30:00.607 component-a.js:30 component-a has been rendered
09:30:00.607 component-b.js:19 component-b is about to be rendered
09:30:00.608 component-b.js:30 component-b has been rendered
09:30:00.608 my-app.js:30 my-app has been rendered
在component-a中打开Shadow DOM会更改渲染。
@Component({
tag: 'component-a',
shadow: true
})
控制台输出更改为:
09:33:22.840 my-app.js:19 my-app is about to be rendered
09:33:22.842 component-a.js:19 component-a is about to be rendered
09:33:22.843 component-b.js:19 component-b is about to be rendered
09:33:22.843 component-b.js:30 component-b has been rendered
09:33:22.844 component-c.js:19 component-c is about to be rendered
09:33:22.845 component-c.js:30 component-c has been rendered
09:33:22.845 component-a.js:30 component-a has been rendered
09:33:22.845 my-app.js:30 my-app has been rendered
现在在渲染组件a和组件c之前先渲染组件b。我不确定使用Shadow DOM渲染页面如何影响此更改。
答案 0 :(得分:1)
在我的测试中,每个请求的渲染顺序可以是三个不同的顺序之一。在任何组件上启用Shadow DOM时,我都看不到任何变化。
我使用了相同的3个组件,并刷新了页面几次。这是三种不同的输出:
Component A is about to be rendered
Component B is about to be rendered
Component B has been rendered
Component C is about to be rendered
Component C has been rendered
Component A has been rendered
-- Hard Refresh --
Component A is about to be rendered
Component C is about to be rendered
Component C has been rendered
Component A has been rendered
Component B is about to be rendered
Component B has been rendered
-- Hard Refresh --
Component B is about to be rendered
Component B has been rendered
Component A is about to be rendered
Component C is about to be rendered
Component C has been rendered
Component A has been rendered
实际上,只要遵循Lifecycle Hierarchy,就可以按照什么顺序渲染它们(至少对于componentDidLoad
方法而言)。