复制 => 运行 => 查看结果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vue生命周期学习</title>
<script src="https://unpkg.com/vue@3"></script>
</head>
<body>
<div id="app">
<h1>{{message}}</h1>
</div>
</body>
<script>
const { createApp } = Vue
var app = createApp({
data() {
return {
message: 'Vue的生命周期'
}
},
beforeCreate: function () {
console.group('------beforeCreate创建前状态------');
console.log("%c%s", "color:red", "el : " + this.$el);
console.log("%c%s", "color:red", "data : " + JSON.stringify(this.$data));
console.log("%c%s", "color:red", "message: " + this.message)
},
created: function () {
console.group('------created创建完毕状态------');
console.log("%c%s", "color:red", "el : " + this.$el);
console.log("%c%s", "color:red", "data : " + JSON.stringify(this.$data));
console.log("%c%s", "color:red", "message: " + this.message);
},
beforeMount: function () {
console.group('------beforeMount挂载前状态------');
console.log("%c%s", "color:red", "el : " + (this.$el));
console.log('el 为', this.$el);
},
mounted: function () {
console.group('------mounted 挂载结束状态------');
console.log("%c%s", "color:red", "el : " + this.$el);
console.log('el 为', this.$el);
},
})
app.mount('#app')
</script>
</html>
%c 给输出指定颜色, 比如
var str = "%c hello %c world";
var arg1 = "color: #fadfa3; background: #030307; padding:5px 0;";
var arg2 = "background: pink; padding:5px 0;";
console.log(str, arg1, arg2)
applyOptions 中执行 beforeCreate, created
beforeCreate
if (options.beforeCreate) {
callHook(options.beforeCreate, instance, LifecycleHooks.BEFORE_CREATE)
}
中间执行函数: 给 vue instance 挂载 options , 使其有 data 之类的
created 此时 instance 中挂载了 data 等 options
if (created) {
callHook(created, instance, LifecycleHooks.CREATED)
}
componentUpdateFn 中执行 beforeMount, mounted
beforeMount
if (bm) {
invokeArrayFns(bm)
}
中间执行: patch(null, sunTree) => processElement => el = vnode.el = hostCreateElement(vnode.type) 给 vnode 添加 el
mounted 此时 $el 上已存在值了
if (m) {
queuePostRenderEffect(m, parentSuspense)
}
更新函数逻辑
const componentUpdateFn = () => {
if (!instance.isMounted) {
if (bm) {
invokeArrayFns(bm)
}
patch(null, sunTree)
if (m) {
queuePostRenderEffect(m, parentSuspense)
}
} else {
if (bu) {
invokeArrayFns(bu)
}
patch(prevTree, nextTree)
if (u) {
queuePostRenderEffect(u, parentSuspense)
}
}
}
参考 https://segmentfault.com/a/1190000011381906
|