vue的生命周期
beforeCreated阶段
initLifecycle(vm)
initEvents(vm)
initRender(vm)
此时el, data, 以及页面数据为空
created阶段
initInjections(vm)
initState(vm)
initProvide(vm)
实例化创建完成
此时data与数据进行绑定,但dom尚未生成
beforeMount阶段
判断是否有el,没有就会停止生命周期,知道调用vm.$mount(el)
然后判断是否有template,有就编辑模板里的内容,否则会编译外部html的内容
vue中还有一个render函数,它是以createElement作为参数,然后做渲染操作,而且我们可以直接嵌入JSX
mounted阶段
vue实例对象添加$el成员,并且将虚拟dom替换掉挂载的dom元素
这里会有个判断逻辑,如果是外部 new Vue({}) 的话,不会存在 $vnode ,所以直接执行 mounted 钩子了。
如果有子组件的话,会递归挂载子组件,只有当所有子组件全部挂载完毕,才会执行根组件的挂载钩子。
<div id="app">
<p @click="handleChange">{{message}}</p>
<keep-alive>
<my-components msg="hello" v-if="show"></my-components>
</keep-alive>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
var child = {
template: '<div>from child: {{msg}}{{childMsg}}</div>',
props: ['msg'],
data: function(){
return {
childMsg: 'child1'
}
},
created: function(){
console.group('child create 更新前状态===============》');
},
mounted: function(){
console.group('child mounted 更新前状态===============》');
},
deactivated: function () {
console.group('deactivated 更新前状态===============》');
console.log('component deactivated!');
},
activated: function () {
console.group('activated 更新前状态===============》');
console.log('component activated');
}
}
var app = new Vue({
el: '#app',
data: function() {
return {
message: 'father',
show: true
}
},
beforeCreate: function() {
console.group('beforeCreate状态==========================')
var state = {
'el': this.$el,
'data': this.$data,
'message': this.message
}
console.log(state)
},
created: function() {
console.group('created状态==========================')
var state = {
'el': this.$el,
'data': this.$data,
'message': this.message
}
console.log(state)
},
beforeMount: function() {
console.group('beforeMount状态==========================')
var state = {
'el': this.$el,
'data': this.$data,
'message': this.message
}
console.log(state)
},
mounted: function() {
console.group('mounted状态==========================')
var state = {
'el': this.$el,
'data': this.$data,
'message': this.message
}
console.log(state)
},
methods: {
handleChange (){
this.message = '123'
}
},
beforeUpdate: function() {
console.group('beforeUpdate 更新前状态===============》');
var state = {
'el': this.$el,
'data': this.$data,
'message': this.message
}
console.log(state);
this.message = '456'
this.show = false
},
updated: function() {
console.group('updated 更新完成状态===============》');
var state = {
'el': this.$el,
'data': this.$data,
'message': this.message
}
console.log(state);
},
beforeDestroy: function() {
console.group('beforeDestroy 销毁前状态===============》');
var state = {
'el': this.$el,
'data': this.$data,
'message': this.message
}
console.log(state);
},
destroyed: function() {
console.group('destroyed 销毁完成状态===============》');
var state = {
'el': this.$el,
'data': this.$data,
'message': this.message
}
console.log(state);
},
components: {
'my-components': child
}
})
</script>
好记性不如烂笔头,看到自己觉得应该记录的知识点,结合自己的理解进行记录,用于以后回顾。

浙公网安备 33010602011771号