4

我试图了解使用 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'
})

每个组件在其每个生命周期方法中都有控制台语句。当页面在浏览器中加载而没有任何打开 shadow 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

component-b 现在在 component-a 和 component-c 都被渲染之前被渲染。我不确定使用 Shadow DOM 渲染页面如何影响此更改。

4

1 回答 1

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方法),它们的呈现顺序可能并不重要。

于 2018-09-19T13:13:50.987 回答