You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import type VNode from 'core/vdom/vnode'
/**
* Runtime helper for resolving raw children VNodes into a slot object.
*/
export function resolveSlots (
children: ?Array<VNode>,
context: ?Component
): { [key: string]: Array<VNode> } {
if (!children || !children.length) {
return {}
}
const slots = {}
for (let i = 0, l = children.length; i < l; i++) {
const child = children[i]
const data = child.data
// remove slot attribute if the node is resolved as a Vue slot node
if (data && data.attrs && data.attrs.slot) {
delete data.attrs.slot
}
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.fnContext === context) &&
data && data.slot != null
) {
const name = data.slot
const slot = (slots[name] || (slots[name] = []))
if (child.tag === 'template') {
slot.push.apply(slot, child.children || [])
} else {
slot.push(child)
}
} else {
(slots.default || (slots.default = [])).push(child)
}
}
// ignore slots that contains only whitespace
for (const name in slots) {
if (slots[name].every(isWhitespace)) {
delete slots[name]
}
}
// 返回插槽的内容,VNode对象
return slots
}
function isWhitespace (node: VNode): boolean {
return (node.isComment && !node.asyncFactory) || node.text === ' '
}
那么谁使用$slots呢,显然是comp1组件的渲染函数,打印其渲染函数:
function anonymous(
) {
with(this){return _c('div',[_t("default")],2)}
}
一、插槽有哪几类?
1. 默认插槽
父组件:
子组件:
2. 具名插槽
父组件:
子组件:
3. 作用域插槽
父组件:
子组件:
二、插槽原理
原理简述
当子组件vm 实例化时,获取到父组件传入的slot 标签的内容,存放在vm.$slot 中,默认插槽为vm.$slot.default,具名插槽为vm.$slot.xxx,xxx 为插槽名,当组件执行渲染函数时候,遇到slot 标签,使用$slot 中的内容进行替换,此时可以为插槽传递数据,若存在数据,则可称该插槽为作用域插槽。
运作流程分析
调试demo代码:
可以从render函数追溯源码:
core/instance/render.js
继续追溯
resolveSlots
函数,这个函数是从父组件中获取渲染节点VNode,存入default,这就是默认插槽的内容。函数renderContext
参数就是父组件实例,显然如果有动态内容要从它里面获取。src/core/instance/render-helpers/resolve-slots.js
那么谁使用$slots呢,显然是
comp1
组件的渲染函数,打印其渲染函数:这里的
_t
源码src/core/instance/render-helpers/index.js中可以找到是renderSlot()
函数的别名,其函数的源码如下:src/core/instance/render-helpers/render-slot.js
The text was updated successfully, but these errors were encountered: