File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ title : Vue源码——初始化initLifecycle
3
+ date : 2023-12-23T12:25:31Z
4
+ summary :
5
+ tags : []
6
+ ---
7
+
8
+ ## 前言
9
+ 在上一篇文章中,我们外到内了解了` Vue ` 是怎么样实例化出来的,以及` Vue ` 的初始化做的事情,在` _init ` 中调用了数个初始化函数,我们逐一地深入来理解这些函数。
10
+
11
+ ## initLifecycle分析
12
+ ```
13
+ export function initLifecycle (vm: Component) {
14
+ const options = vm.$options
15
+
16
+ let parent = options.parent
17
+ if (parent && !options.abstract) {
18
+ while (parent.$options.abstract && parent.$parent) {
19
+ parent = parent.$parent
20
+ }
21
+ parent.$children.push(vm)
22
+ }
23
+ ...
24
+ ```
25
+ 这里判断当前组件不是<a href = " /detail/1072" target = " _black" >抽象组件</a >或是存在着父级,那么就` while ` 向上层循环,如果父级是抽象组件或是存在父级,继续向上循环直到找到一个非抽象组件的父级为止,然后将` vm ` 添加给这个最顶层父级的` $children ` 数组中。
26
+ ```
27
+ ...
28
+ // 父级实例
29
+ vm.$parent = parent
30
+ // 根实例
31
+ vm.$root = parent ? parent.$root : vm
32
+ // 子实例
33
+ vm.$children = []
34
+ // ref引用
35
+ vm.$refs = {}
36
+
37
+ vm._watcher = null
38
+ vm._inactive = null
39
+ vm._directInactive = false
40
+ vm._isMounted = false
41
+ vm._isDestroyed = false
42
+ vm._isBeingDestroyed = false
43
+ }
44
+ ```
45
+ 有意思的是` vm.$root ` 属性,当当前实例存在的父级时,他的` $root ` 就是父级的` $root ` ,那么有人就会问了,为什么是直接赋这个值而不用像上文一样一层层遍历呢,举一个例子:` $root ` 代表你的祖先,` $parent ` 和` vm ` 代表你爸爸和你,你的祖先就一定是你爸爸的祖先。而如果当前没有父级,那么根实例就是它自己,他以后儿孙的祖先就是它了。
46
+ 而后就是对` vm ` 对象上的属性进行简单的赋值,这里就不一一介绍他们的用途。
47
+ ## 总结
48
+ ` initLifecycle ` 函数主要是给` vm ` 对象添加一系列的属性,以` $ ` 开头的公有属性,以及以` _ ` 开头的表示私有属性。
49
+
You can’t perform that action at this time.
0 commit comments