代码背景 在打印如下代码的时候
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<title>Document</title>
<style>
#app{
margin-bottom: 1em;
}
body {
font-size: 1.5em;
}
</style>
</head>
<body>
<div >
<h1>{{count}}</h1>
<button @click="updateEvent">Update</button>
<button >删除当前元素</button>
</div>
<script>
var vm=new Vue({
el:'#app',
data:{
count:0
},
methods:{
updateEvent:function () {
this.count+=1;
}
},
beforeCreate:function () {
//元素刚被建立,属性计算之前
console.log("beforeCreated -this.count",this.count);
//el 是整个'#app' 元素和里面的内容
console.log("beforeCreated -this.$el",this.$el);
},
created:function () {
//元素实例已经建立,属性已经绑定,但是DOM没生成
console.log('created- this.count',this.count);
console.log('created- this.$el',this.$el);
},
beforeMount:function () {
//模版 template 编译活挂载至 HTML之前
console.log('beforeMount -this.$el'+this.$el.innerHTML);
console.log('beforeMount -this.$el'+this.$el);
},
mounted:function () {
//模版 template 编译活挂载至 HTML之后
console.log('mounted -this.$el'+this.$el.innerHTML);
},
beforeUpdate:function () {
//元素被更新之前
console.log('beforeUpdate:',
this.$el.querySelector('h1').innerText,
this.count);
},
updated:function () {
//元素更新 之后
console.log('updated:', this.$el)
},
beforeDestroy:function(){
//移除 vue instance 之前
console.log('beforeDestroy')
},
destroyed:function () {
//移除Vue instance 之后
console.log('destroyed');
}
});
document.getElementById('del').addEventListener('click',function () {
vm.$destroy();
})
</script>
</body>
</html>
摘出来
beforeMount:function () {
//模版 template 编译活挂载至 HTML之前
console.log('beforeMount -this.$el'+this.$el.innerHTML);
console.log('beforeMount -this.$el'+this.$el);
},
发现
this.$el打印出来是HTMLDivElement 什么鬼。。
发现后面加innerHTML就可以打印出来正常元素了
打印记录
<!--打印结果-->
beforeCreated -this.count undefined
beforeCreated -this.$el undefined
<!--元素实例已经建立,属性已经绑定,但是DOM没生成-->
created- this.count 0
created- this.$el undefined
<!-- 模版 template 编译活挂载至 HTML之前-->
beforeMount -this.$el
<h1>{{count}}</h1>
<button @click="updateEvent">Update</button>
<button >删除当前元素</button>
//模版 template 编译活挂载至 HTML之后
mounted -this. $el
<h1>0</h1> <button>Update</button> <button >删除当前元素</button>
//点击更新的时候
beforeUpdate: 0 1
updated: 1 1
beforeUpdate: 1 2
updated: 2 2
beforeUpdate: 2 3
updated: 3 3
beforeUpdate: 3 4
updated: 4 4
//点击删除的时候
beforeDestroy
destroyed
之后再点击更新将无效
这个时候我们再去看之前的官网生命周期图理解就会更深刻一点