阅读完这篇博客你会有以下收获:
- slot算法是什么?
- shadow DOM是什么?
- vue slot机制与w3c web component 规范的 shadow DOM渲染结果有何异同?
slot算法
The slotting algorithm assigns nodes of a shadow tree host into slots of that tree.
InputHOST -- a shadow tree host Output All child nodes of HOST are slotted
- LetTREEbeHOST's shadow tree
- LetDEFAULTbe an empty list of nodes
- For each child nodeNODEofHOST, in tree order:
- LetNAMEbeNODE'sslot name
- IfNAMEis missing, addNODEtoDEFAULT
- LetSLOTbe the slot withslot nameNAMEforTREE
- IfSLOTdoes not exist, discard node
- Otherwise, assignNODEtoSLOT
- LetDEFAULT-SLOTbe the thedefault slotforTREE
- IfDEFAULT-SLOTdoes not exist,stop
- Otherwise, assign all nodes inDEFAULTtoDEFAULT-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规范的一个提案,地址位于github.com/w3c/webcomp…
在这个提案中,我们发现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其实一直都在用,例如标签,封装了很多按钮,这就是shadow DOM。
- 两种模式mode:open,closed。属于包含了shadow DOM的内建标签,它的mode就是closed,外部不能通过shadowRoot获取到这个标签的shadow DOM。open模式更适用。
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>
渲染结果:
渲染结果与slot算法十分契合,但是较为奇怪的是,vue的slot机制,不会生成像w3c web component 的shadow DOM。
web component shadow DOM是下面这样:
标签:slot,web,DOM,tree,shadow,Shadow From: https://blog.51cto.com/u_15725382/5735199
- 微信公众号: 大大大前端