Vue-js 源碼分析—— Slots 是如何實現的
今天主要分析 Vue.js 中常用的 Slots 功能是如何設計和實現的。本文將分爲普通插槽、作用域插槽以及 Vue.js 2.6.x 版本的 v-slot 語法三部分進行討論。
本文屬於進階內容,如果有還不懂 Slots 用法的同學,建議先移步 Vue.js 官網進行學習。
1 普通插槽
首先舉一個 Slots 使用的簡單例子。
<template>
<div class="slot-demo">
<slot>this is slot default content text.</slot>
</div>
</template>
直接在頁面上渲染這個組件,效果如下圖所示:
接着,我們對 Slots 裏的內容進行覆蓋。
<slot-demo>this is slot custom content.</slot-demo>
重新渲染後,效果如下圖所示:
Slots 的用法大家肯定都很清楚了,那麼這背後 Vue.js 執行了怎樣的邏輯呢?接下來我們一起看看 Vue.js 底層對 Slots 的具體實現。
1.1 **vm.$slots**
首先看看 Vue.js 的 Component 接口上對 $slots
屬性的定義。
$slots: { [key: string]: Array<VNode> };
多的咱不說,咱直接在控制檯打印一下上面例子中的 $slots
:
接下來講解 Slots 內容渲染以及轉換成上圖對象的過程。
公衆號
1.2 **renderSlot**
看完了具體實例中 Slots 渲染後的 vm.$slots
對象,我們來解析一下 renderSlot
這塊的邏輯,首先我們先看看 renderSlot
函數的參數都有哪些:
export function renderSlot (
name: string, // 插槽名 slotName
fallback: ?Array<VNode>, // 插槽默認內容生成的 vnode 數組
props: ?Object, // props 對象
bindObject: ?Object // v-bind 綁定對象
): ?Array<VNode> {}
這裏我們先不看 scoped-slot 的邏輯,只看普通 slot 的邏輯:
const slotNodes = this.$slots[name]
nodes = slotNodes || fallback
return nodes
這裏拿到this.$slots[name]
的值後做了一個空值判斷,若存在則直接返回其對應的 vnode 數組,否則返回 fallback 。
1.3 **resolveSlots**
看到這,很多人可能不知道 this.$slots
在哪定義的,解釋這個之前,我們要先了解另外一個方法 resolveSlots
。
export function resolveSlots (
children: ?Array<VNode>, // 父節點的 children
context: ?Component // 父節點的上下文,即父組件的 vm 實例
): { [key: string]: Array<VNode> } {}
看完 resolveSlots
的定義後我們接着往後看其中的具體邏輯。
這裏先定義了一個 slots
的空對象,如果 參數children
不存在,直接返回。
const slots = {}
if (!children) {
return slots
}
如果存在,則對 children
進行遍歷操作。
for (let i = 0, l = children.length; i < l; i++) {
const child = children[i]
const data = child.data
// 如果 data.slot 存在,將插槽名稱當做 key,child 當做值直接添加到 slots 中去
if ((child.context === context || child.fnContext === context) &&
data && data.slot != null
) {
const name = data.slot
const slot = (slots[name] || (slots[name] = []))
// child 的 tag 爲 template 標籤的情況
if (child.tag === 'template') {
slot.push.apply(slot, child.children || [])
} else {
slot.push(child)
}
// 如果 data.slot 不存在,則直接將 child 丟到 slots.default 中去
} else {
(slots.default || (slots.default = [])).push(child)
}
}
slots
獲取到值後,會過濾掉只包含空白字符的屬性,然後返回。
// ignore slots that contains only whitespace
for (const name in slots) {
if (slots[name].every(isWhitespace)) {
delete slots[name]
}
}
return slots
// isWhitespace 相關邏輯
function isWhitespace (node: VNode): boolean {
return (node.isComment && !node.asyncFactory) || node.text === ' '
}
1.4 **initRender**
上文解釋了 slots
變量的初始化和賦值過程。接下來介紹的 initRender
方法對 vm.$slots
進行了初始化的過程。
// src/core/instance/render.js
const options = vm.$options
const parentVnode = vm.$vnode = options._parentVnode // the placeholder node in parent tree
const renderContext = parentVnode && parentVnode.context
vm.$slots = resolveSlots(options._renderChildren, renderContext)
genSlot()
看完上面的代碼,肯定有人會問:你這不就只是拿到了一個對象麼,怎麼把其中的內容給解析出來呢?
1.5 **genSlot**
別急,我們接着就來把 Slots 解析的相關邏輯過一過,話不多說,咱直接上代碼:
function genSlot (el: ASTElement, state: CodegenState): string {
const slotName = el.slotName || '"default"' // 取 slotName,若無,則直接命名爲 'default'
const children = genChildren(el, state) // 對 children 進行 generate 操作
let res = `_t(${slotName}${children ? `,${children}` : ''}`
const attrs = el.attrs && `{${el.attrs.map(a => `${camelize(a.name)}:${a.value}`).join(',')}}` // 將 attrs 轉換成對象形式
const bind = el.attrsMap['v-bind'] // 獲取 slot 上的 v-bind 屬性
// 若 attrs 或者 bind 屬性存在但是 children 卻木得,直接賦值第二參數爲 null
if ((attrs || bind) && !children) {
res += `,null`
}
// 若 attrs 存在,則將 attrs 作爲 `_t()` 的第三個參數(普通插槽的邏輯處理)
if (attrs) {
res += `,${attrs}`
}
// 若 bind 存在,這時如果 attrs 存在,則 bind 作爲第三個參數,否則 bind 作爲第四個參數(scoped-slot 的邏輯處理)
if (bind) {
res += `${attrs ? '' : ',null'},${bind}`
}
return res + ')'
}
上面的 slotName
在 processSlot
函數中進行了賦值,並且 父組件編譯階段用到的 slotTarget
也在這裏進行了處理。
// src/compiler/parser/index.js
function processSlot (el) {
if (el.tag === 'slot') {
// 直接獲取 attr 裏面 name 的值
el.slotName = getBindingAttr(el, 'name')
// ...
}
// ...
const slotTarget = getBindingAttr(el, 'slot')
if (slotTarget) {
// 如果 slotTarget 存在則直接取命名插槽的 slot 值,否則直接爲 'default'
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget
if (el.tag !== 'template' && !el.slotScope) {
addAttr(el, 'slot', slotTarget)
}
}
}
隨即在 genData
函數中使用 slotTarget
進行 data
的數據拼接。
if (el.slotTarget && !el.slotScope) {
data += `slot:${el.slotTarget},`
}
此時父組件將生成以下代碼:
with(this) {
return _c('div', [
_c('slot-demo'),
{
attrs: { slot: 'default' },
slot: 'default'
},
[ _v('this is slot custom content.') ]
])
}
然後當 el.tag
爲 slot
的情況,直接執行 genSlot
函數:
else if (el.tag === 'slot') {
return genSlot(el, state)
}
按照我們舉出的例子,子組件最終會生成以下代碼:
with(this) {
// _c => createElement ; _t => renderSlot ; _v => createTextVNode
return _c(
'div',
{
staticClass: 'slot-demo'
},
[ _t('default', [ _v('this is slot default content text.') ]) ]
)
}
2 作用域插槽
上面我們已經瞭解到 Vue.js 對於普通的 Slots 是如何進行處理和轉換的。接下來我們來分析下作用域插槽的實現邏輯。
2.1 **vm.$scopedSlots**
老規矩,先看看 Vue.js 的 Component 接口上對 $scopedSlots
屬性的定義。
$scopedSlots: { [key: string]: () => VNodeChildren };
其中的 VNodeChildren
定義如下:
declare type VNodeChildren = Array<?VNode | string | VNodeChildren> | string;
先來個相關的例子:
<template>
<div class="slot-demo">
<slot text="this is a slot demo , " :msg="msg"></slot>
</div>
</template>
<script>
export default {
name: 'SlotDemo',
data () {
return {
msg: 'this is scoped slot content.'
}
}
}
</script>
然後進行使用:
<template>
<div class="parent-slot">
<slot-demo>
<template slot-scope="scope">
<p>{{ scope.text }}</p>
<p>{{ scope.msg }}</p>
</template>
</slot-demo>
</div>
</template>
效果如下:
從例子中我們能看出用法,子組件的 slot
標籤上綁定 text
以及 :msg
屬性。然後父組件在使用插槽用 slot-scope
屬性去讀取插槽屬性對應的值。
2.2 **processSlot**
提及一下 processSlot
函數對於 slot-scope
的處理邏輯:
let slotScopeif (el.tag === 'template') {
slotScope = getAndRemoveAttr(el, 'scope') // 兼容 2.5 以前版本 slot scope 的用法(這塊有個警告,我直接忽略掉了)
el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope')
} else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) {
el.slotScope = slotScope
}
從上面的代碼我們能看出,Vue.js 直接讀取 slot-scope
屬性並賦值給 AST 抽象語法樹的 slotScope
屬性,而擁有 slotScope
屬性的節點,會直接以插槽名稱 name 爲 key、本身爲 value 的對象形式掛載在父節點的 scopedSlots
屬性上。
else if (element.slotScope) {
currentParent.plain = false
const name = element.slotTarget || '"default"'
(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element
}
然後在 renderMixin
函數中對 vm.$scopedSlots
進行了如下賦值:
// src/core/instance/render.js
if (_parentVnode) { vm.$scopedSlots = _parentVnode.data.scopedSlots || emptyObject}
然後 genData
函數里會進行以下邏輯處理:
if (el.scopedSlots) { data += `${genScopedSlots(el, el.scopedSlots, state)},`}
2.3 **genScopedSlots & genScopedSlot**
緊接着我們來看看 genScopedSlots
函數中的邏輯:
function genScopedSlots (
slots: { [key: string]: ASTElement },
state: CodegenState
): string {
// 對 el.scopedSlots 對象進行遍歷,執行 genScopedSlot,且將結果用逗號進行拼接
// _u => resolveScopedSlots (具體邏輯下面一個小節進行分析)
return `scopedSlots:_u([${
Object.keys(slots).map(key => {
return genScopedSlot(key, slots[key], state)
}).join(',')
}])`
}
然後我們再來看看 genScopedSlot
函數是如何生成 render function 字符串的:
function genScopedSlot (
key: string,
el: ASTElement,
state: CodegenState
): string {
if (el.for && !el.forProcessed) {
return genForScopedSlot(key, el, state)
}
// 函數參數爲標籤上 slot-scope 屬性對應的值 (getAndRemoveAttr(el, 'slot-scope'))
const fn = `function(${String(el.slotScope)}){` +
`return ${el.tag === 'template'
? el.if
? `${el.if}?${genChildren(el, state) || 'undefined'}:undefined`
: genChildren(el, state) || 'undefined'
: genElement(el, state)
}}`
// key 爲插槽名稱,fn 爲生成的函數代碼
return `{key:${key},fn:${fn}}`
}
我們把上面例子的 $scopedSlots
在控制檯打印一下,結果如下:
上面例子中父組件最終會生成如下代碼:
with(this){
// _c => createElement ; _u => resolveScopedSlots
// _v => createTextVNode ; _s => toString
return _c('div',
{ staticClass: 'parent-slot' },
[_c('slot-demo',
{ scopedSlots: _u([
{
key: 'default',
fn: function(scope) {
return [
_c('p', [ _v(_s(scope.text)) ]),
_c('p', [ _v(_s(scope.msg)) ])
]
}
}])
}
)]
)
}
2.4 **renderSlot(slot-scope) & renderSlot**
上面我們提及對於插槽渲染邏輯的時候忽略了 slot-scope
的相關邏輯,這裏我們來看看這部分內容:
export function renderSlot (
name: string,
fallback: ?Array<VNode>,
props: ?Object,
bindObject: ?Object
): ?Array<VNode> {
const scopedSlotFn = this.$scopedSlots[name]
let nodes
if (scopedSlotFn) { // scoped slot
props = props || {}
// ...
nodes = scopedSlotFn(props) || fallback
}
// ...
return nodes
}
resolveScopedSlots()
這裏 renderHelps
函數里面的 _u
,即 resolveScopedSlots
,其邏輯如下:
export function resolveScopedSlots (
fns: ScopedSlotsData, // Array<{ key: string, fn: Function } | ScopedSlotsData>
res?: Object
): { [key: string]: Function } {
res = res || {}
// 遍歷 fns 數組,生成一個 `key 爲插槽名稱,value 爲函數` 的對象
for (let i = 0; i < fns.length; i++) {
if (Array.isArray(fns[i])) {
resolveScopedSlots(fns[i], res)
} else {
res[fns[i].key] = fns[i].fn
}
}
return res
}
genSlot
函數上面我已經講解過,要看請往上翻閱。結合我們的例子,子組件則會生成以下代碼:
with(this) {
return _c(
'div',
{
staticClass: 'slot-demo'
},
[
_t('default', null, { text: 'this is a slot demo , ', msg: msg })
]
)
}
到目前爲止,對於普通插槽和作用域插槽已經談的差不多了。接下來,我們將一起看看 Vue.js 2.6.x 版本的 v-slot
語法。
3 v-slot
3.1 基本用法
Vue.js 2.6.x 已經出來有一段時間了,其中對於插槽這塊則是放棄了作用域插槽推薦寫法,直接改成了 v-slot
指令形式的推薦寫法,當然這只是個語法糖而已。
在看具體實現邏輯前,我們先通過一個例子來先了解下其基本用法:
<template>
<div class="slot-demo">
<slot >this is demo slot.</slot>
<slot text="this is a slot demo , " :msg="msg"></slot>
</div>
</template>
<script>
export default {
name: 'SlotDemo',
data () {
return {
msg: 'this is scoped slot content.'
}
}
}
</script>
然後:
<template>
<slot-demo>
<template v-slot:demo>this is custom slot.</template>
<template v-slot="scope">
<p>{{ scope.text }}{{ scope.msg }}</p>
</template>
</slot-demo>
</template>
3.2 相同與區別
3.2.1 **$slots & $scopedSlots**
$slots
這塊邏輯沒變,還是沿用的以前的代碼:
// $slots
const options = vm.$options
const parentVnode = vm.$vnode = options._parentVnode
const renderContext = parentVnode && parentVnode.context
vm.$slots = resolveSlots(options._renderChildren, renderContext)
$scopedSlots 這塊則進行了改造,執行了 normalizeScopedSlots() 並接收其返回值爲 $scopedSlots 的值
if (_parentVnode) {
vm.$scopedSlots = normalizeScopedSlots(
_parentVnode.data.scopedSlots,
vm.$slots,
vm.$scopedSlots
)
}
接着,我們來會一會 normalizeScopedSlots
,首先我們先看看它的定義:
export function normalizeScopedSlots (
slots: { [key: string]: Function } | void, // 某節點 data 屬性上 scopedSlots
normalSlots: { [key: string]: Array<VNode> }, // 當前節點下的普通插槽
prevSlots?: { [key: string]: Function } | void // 當前節點下的特殊插槽
): any {}
首先,如果 slots
不存在,則直接返回一個空對象 {}
:
if (!slots) {
res = {}
}
若 prevSlots
存在,且滿足系列條件的情況,則直接返回 prevSlots
:
const hasNormalSlots = Object.keys(normalSlots).length > 0 // 是否擁有普通插槽
const isStable = slots ? !!slots.$stable : !hasNormalSlots // slots 上的 $stable 值
const key = slots && slots.$key // slots 上的 $key 值
else if (
isStable &&
prevSlots &&
prevSlots !== emptyObject &&
key === prevSlots.$key && // slots $key 值與 prevSlots $key 相等
!hasNormalSlots && // slots 中沒有普通插槽
!prevSlots.$hasNormal // prevSlots 中沒有普通插槽
) {
return prevSlots
}
注:這裏的 key
, hasNormal
, $stable
是直接使用 Vue.js 內部對 Object.defineProperty
封裝好的 def
方法進行賦值的。
def(res, '$stable', isStable)
def(res, '$key', key)
def(res, '$hasNormal', hasNormalSlots)
// 否則,則對 slots 對象進行遍歷,操作 normalSlots ,賦值給 key 爲 key,value 爲 normalizeScopedSlot 返回的函數 的對象 res
let res
else {
res = {}
for (const key in slots) {
if (slots[key] && key[0] !== '$') {
res[key] = normalizeScopedSlot(normalSlots, key, slots[key])
}
}
}
隨後再次對 normalSlots
進行遍歷,若 normalSlots
中的 key
在 res
找不到對應的 key
,則直接進行 proxyNormalSlot
代理操作,將 normalSlots
中的 slot
掛載到 res
對象上。
for (const key in normalSlots) {
if (!(key in res)) {
res[key] = proxyNormalSlot(normalSlots, key)
}
}
function proxyNormalSlot(slots, key) {
return () => slots[key]
}
接着,我們看看 normalizeScopedSlot
函數都做了些什麼事情。該方法接收三個參數,第一個參數爲 normalSlots
,第二個參數爲 key
,第三個參數爲 fn
。
function normalizeScopedSlot(normalSlots, key, fn) {
const normalized = function () {
// 若參數爲多個,則直接使用 arguments 作爲 fn 的參數,否則直接傳空對象作爲 fn 的參數
let res = arguments.length ? fn.apply(null, arguments) : fn({})
// fn 執行返回的 res 不是數組,則是單 vnode 的情況,賦值爲 [res] 即可
// 否則執行 normalizeChildren 操作,這塊主要對針對 slot 中存在 v-for 操作
res = res && typeof res === 'object' && !Array.isArray(res)
? [res] // single vnode
: normalizeChildren(res)
return res && (
res.length === 0 ||
(res.length === 1 && res[0].isComment) // slot 上 v-if 相關處理
) ? undefined
: res
}
// v-slot 語法糖處理
if (fn.proxy) {
Object.defineProperty(normalSlots, key, {
get: normalized,
enumerable: true,
configurable: true
})
}
return normalized
}
3.2.2 renderSlot
這塊邏輯處理其實和之前是一樣的,只是刪除了一些警告的代碼而已。這點這裏就不展開敘述了。
3.2.3 processSlot
首先,這裏解析 slot
的方法名從 processSlot
變成了 processSlotContent
,但其實前面的邏輯和以前是一樣的。只是新增了一些對於 v-slot 的邏輯處理,下面我們就來捋捋這塊。過具體邏輯前,我們先看一些相關的正則和方法。
- 相關正則 & functions
// dynamicArgRE 動態參數匹配
const dynamicArgRE = /^\[.*\]$/ // 匹配到 '[]' 則爲 true,如 '[ item ]'
// slotRE 匹配 v-slot 語法相關正則
const slotRE = /^v-slot(:|$)|^#/ // 匹配到 'v-slot' 或 'v-slot:' 則爲 true
// getAndRemoveAttrByRegex 通過正則匹配綁定的 attr 值
export function getAndRemoveAttrByRegex (
el: ASTElement,
name: RegExp //
) {
const list = el.attrsList // attrsList 類型爲 Array<ASTAttr>
// 對 attrsList 進行遍歷,若有滿足 RegExp 的則直接返回當前對應的 attr
// 若參數 name 傳進來的是 slotRE = /^v-slot(:|$)|^#/
// 那麼匹配到 'v-slot' 或者 'v-slot:xxx' 則會返回其對應的 attr
for (let i = 0, l = list.length; i < l; i++) {
const attr = list[i]
if (name.test(attr.name)) {
list.splice(i, 1)
return attr
}
}
}
ASTAttr 接口定義
declare type ASTAttr = {
name: string;
value: any;
dynamic?: boolean;
start?: number;
end?: number
};
// createASTElement 創建 ASTElement
export function createASTElement (
tag: string, // 標籤名
attrs: Array<ASTAttr>, // attrs 數組
parent: ASTElement | void // 父節點
): ASTElement {
return {
type: 1,
tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
rawAttrsMap: {},
parent,
children: []
}
}
// getSlotName 獲取 slotName
function getSlotName (binding) {
// 'v-slot:item' 匹配獲取到 'item'
let name = binding.name.replace(slotRE, '')
if (!name) {
if (binding.name[0] !== '#') {
name = 'default'
} else if (process.env.NODE_ENV !== 'production') {
warn(
`v-slot shorthand syntax requires a slot name.`,
binding
)
}
}
// 返回一個 key 包含 name,dynamic 的對象
// 'v-slot:[item]' 匹配然後 replace 後獲取到 name = '[item]'
// 進而進行動態參數進行匹配 dynamicArgRE.test(name) 結果爲 true
return dynamicArgRE.test(name)
? { name: name.slice(1, -1), dynamic: true } // 截取變量,如 '[item]' 截取後變成 'item'
: { name: `"${name}"`, dynamic: false }
}
**processSlotContent**
這裏我們先看看 Slots 對於 template 是如何處理的:
if (el.tag === 'template') {
// 匹配綁定在 template 上的 v-slot 指令,這裏會匹配到對應 v-slot 的 attr(類型爲 ASTAttr)
const slotBinding = getAndRemoveAttrByRegex(el, slotRE)
// 若 slotBinding 存在,則繼續進行 slotName 的正則匹配
// 隨即將匹配出來的 name 賦值給 slotTarget,dynamic 賦值給 slotTargetDynamic
// slotScope 賦值爲 slotBinding.value 或者 '_empty_'
if (slotBinding) {
const { name, dynamic } = getSlotName(slotBinding)
el.slotTarget = name
el.slotTargetDynamic = dynamic
el.slotScope = slotBinding.value || emptySlotScopeToken
}
}
如果不是 template,而是綁定在 component 上的話,對於 **v-slot**
指令和 **slotName**
的匹配操作是一樣的,不同點在於這裏需要將組件的 children 添加到其默認插槽中去。
else {
// v-slot on component 表示默認插槽
const slotBinding = getAndRemoveAttrByRegex(el, slotRE)
// 將組件的 children 添加到其默認插槽中去
if (slotBinding) {
// 獲取當前組件的 scopedSlots
const slots = el.scopedSlots || (el.scopedSlots = {})
// 匹配拿到 slotBinding 中 name,dynamic 的值
const { name, dynamic } = getSlotName(slotBinding)
// 獲取 slots 中 key 對應匹配出來 name 的 slot
// 然後再其下面創建一個標籤名爲 template 的 ASTElement,attrs 爲空數組,parent 爲當前節點
const slotContainer = slots[name] = createASTElement('template', [], el)
// 這裏 name、dynamic 統一賦值給 slotContainer 的 slotTarget、slotTargetDynamic,而不是 el
slotContainer.slotTarget = name
slotContainer.slotTargetDynamic = dynamic
// 將當前節點的 children 添加到 slotContainer 的 children 屬性中
slotContainer.children = el.children.filter((c: any) => {
if (!c.slotScope) {
c.parent = slotContainer
return true
}
})
slotContainer.slotScope = slotBinding.value || emptySlotScopeToken
// 清空當前節點的 children
el.children = []
el.plain = false
}
}
這樣處理後我們就可以直接在父組件上面直接使用 **v-slot**
指令去獲取 Slots 綁定的值。
舉個官方例子:
Default slot with text
<foo>
<template slot-scope="{ msg }">
{{ msg }}
</template>
</foo>
<foo v-slot="{ msg }">
{{ msg }}
</foo>
Default slot with element
<foo>
<div slot-scope="{ msg }">
{{ msg }}
</div>
</foo>
<foo v-slot="{ msg }">
<div>
{{ msg }}
</div>
</foo>
3.2.4 **genSlot**
在這塊邏輯也沒發生本質性的改變,唯一一個改變就是爲了支持 **v-slot**
動態參數做了些改變,具體如下:
// old
const attrs = el.attrs && `{${el.attrs.map(a => `${camelize(a.name)}:${a.value}`).join(',')}}`
// new
// attrs、dynamicAttrs 進行 concat 操作,並執行 genProps 將其轉換成對應的 generate 字符串
const attrs = el.attrs || el.dynamicAttrs
? genProps(
(el.attrs || []).concat(el.dynamicAttrs || []).map(attr => ({
// slot props are camelized
name: camelize(attr.name),
value: attr.value,
dynamic: attr.dynamic
}))
)
: null
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/H6EBvlHRh64EQpMf0RxVqw