介绍
生命周期钩子 = 生命周期函数 = 生命周期事件。
生命周期函数的主要分类

根据上面这张图,我们把生命周期函数主要分为三类。
1、创建期间的生命周期函数
-
beforeCreate:实例刚在内存中被创建出来,此时,还没有初始化好 data 和 methods 属性
-
created:实例已经在内存中创建OK,此时 data 和 methods 已经创建OK,此时还没有开始 编译模板。我们可以在这里进行Ajax请求。
-
beforeMount:此时已经完成了模板的编译,但是还没有挂载到页面中
-
mounted:此时,已经将编译好的模板,挂载到了页面指定的容器中显示。(mounted之后,表示真实DOM渲染完了,可以操作DOM了)
举例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <title>Title</title> <script src="vue2.5.16.js"></script> </head>
<body> <div id="app"> </div> </body>
<script> new Vue({ el: '#app', data: { msg: 'hello vuejs' }, beforeCreate: function () { console.log('01 beforeCreate', this.msg); },
created: function () { console.log('02 created', this.msg); },
beforeMount: function () { console.log('03 beforeMount', this.msg); },
mounted: function () { console.log('04 mounted', this.msg); } });
</script>
</html>
|
打印结果:

运行期间的生命周期函数
PS:数据发生变化时,会触发这两个方法。不过,我们一般用watch来做。
举例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <title>Title</title> <script src="vue2.5.16.js"></script> </head>
<body> <div id="app"> <input type="button" value="修改flag" @click="myMethod"> <h3 id="h3">{{ flag }}</h3> </div> </body>
<script> new Vue({ el: '#app', data: { msg: 'hello vue', flag: false },
methods: { myMethod: function () { this.flag = true; } },
beforeUpdate() { console.log('-------------05 beforeUpdate', this.msg);
console.log('界面上DOM元素显示的内容:' + document.getElementById('h3').innerText) console.log('data 中的 msg 数据:' + this.flag) }, updated() { console.log('-------------06 updated', this.msg);
console.log('界面上DOM元素显示的内容:' + document.getElementById('h3').innerText) console.log('data 中的 msg 数据:' + this.flag) } });
</script>
</html>
|
当我们点击按钮后,运行效果是:

可以看出:
3、销毁期间的生命周期函数
PS:可以在beforeDestory里清除定时器、或清除事件绑定。
生命周期函数图解

PS:图片来自网络。