简单理解slot算法和shadow DOM

阅读完这篇博客你会有如下收获:html

  • 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.vue

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

  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.git

这是w3c web components规范的一个提案,地址位于https://github.com/w3c/webcomponents/blob/gh-pages/proposals/Slots-Proposal.mdgithub

在这个提案中,咱们发现shadow DOM和shadow Tree这两个概念,关于它们的规范,在这里:w3c.github.io/webcomponen…web

mdn上关于shadow DOM的一篇特别好的文章:developer.mozilla.org/en-US/docs/…算法

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

几个shadow DOM的专业术语:ide

  • Shadow host: shadow DOM要链接的普通DOM节点。
  • Shadow tree: shadow DOM里的DOM树。
  • Shadow boundary: Shadow DOM结束的地方,也是普通DOM开始的地方。
  • Shadow root:shadow tree的根节点。

Shadow DOM知识点:this

  • 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
相关文章
相关标签/搜索