簡單理解slot演算法和shadow DOM

趁你還年輕233發表於2019-02-25

閱讀完這篇部落格你會有以下收穫:

  • slot演算法是什麼?
  • shadow DOM是什麼?
  • vue slot機制與w3c web component 規範的 shadow DOM渲染結果有何異同?

image

slot演算法

The slotting algorithm assigns nodes of a shadow tree host into slots of that tree.

Input HOST -- a shadow tree host Output All child nodes of HOST are slotted

  1. Let TREE be HOST's shadow tree
  2. Let DEFAULT be an empty list of nodes
  3. For each child node NODE of HOST, in tree order:
  4. Let NAME be NODE's slot name
  5. If NAME is missing, add NODE to DEFAULT
  6. Let SLOT be the slot with slot name NAME for TREE
  7. If SLOT does not exist, discard node
  8. Otherwise, assign NODE to SLOT
  9. Let DEFAULT-SLOT be the the default slot for TREE
  10. If DEFAULT-SLOT does not exist, stop
  11. Otherwise, assign all nodes in DEFAULT to DEFAULT-SLOT.

When each node is assigned to a slot, this slot is also added to the node's destination insertion points list.

這是w3c web components規範的一個提案,地址位於https://github.com/w3c/webcomponents/blob/gh-pages/proposals/Slots-Proposal.md

在這個提案中,我們發現shadow DOM和shadow Tree這兩個概念,關於它們的規範,在這裡:w3c.github.io/webcomponen…

mdn上關於shadow DOM的一篇特別好的文章:developer.mozilla.org/en-US/docs/…

Shadow DOM : attach a hidden separated DOM to an element.

幾個shadow DOM的專業術語:

  • Shadow host: shadow DOM要連線的普通DOM節點。
  • Shadow tree: shadow DOM裡的DOM樹。
  • Shadow boundary: Shadow DOM結束的地方,也是普通DOM開始的地方。
  • Shadow root:shadow tree的根節點。

Shadow DOM知識點:

  • shadow DOM和普通DOM一樣可以新增子節點設定屬性,但是shadow DOM內部的程式碼不能影響到外部的任何東西。
  • shadow DOM其實一直都在用,例如
  • 兩種模式mode:open,closed。

shadow DOM的作用是什麼:增強元件內聚性

An important aspect of web components is encapsulation — being able to keep the markup structure, style, and behavior hidden and separate from other code on the page so that different parts do not clash, and the code can be kept nice and clean.

vue demo: component.vue -> shadow host

<slot></slot>
<slot name="foo"></slot>
<slot name="bar"></slot>
複製程式碼

page.vue -> shadow Tree

<span>+</span>
<span slot="foo">-</span>
<span slot="bar">2</span>
<span slot="bar">3</span>
複製程式碼

渲染結果:

image

渲染結果與slot演算法十分契合,但是較為奇怪的是,vue的slot機制,不會生成像w3c web component 的shadow DOM。

web component shadow DOM是下面這樣:

image

相關文章