前言
此文章为个人分析源码的笔记,如果有解释不到位的地方,尽管评论。
demo地址
实例
const { render, h } = Vue
const MyComponent = {
setup(props, ctx) {
return () => h('div', {}, ctx.slots.default(), ctx.slots.header())
}
}
const VueComponent = {
setup() {
return () =>
h(MyComponent, null, {
default: () => h('p', { color: 'red' }, '123'),
header: () => h('h2', null, '345')
})
}
}
render(h(VueComponent), document.getElementById('app'))
源码分析
-
通过上述的实例,在生成组件
MyComponent
的时候,会在实例(instance
)上产生slot
属性
-
有一个观点
组件的孩子一定是slot
。下列图例就是slot孩子
- 接下来的目的就是将children上的属性都赋值给
slots
属性
-
最后使用的时候,直接可以通过
ctx.slots
来使用。会将属性slots
作为参数来传递
-
上述就是
slot
执行过程,就是将children的值都赋值给slots
属性,使用的时候直接到slots
属性上获取
结束
slot
的原理很简单,就分析这么多了。下一篇我们来分析ref
如何赋值的