前端基础之《Vue(7)—生命周期》
一、什么是生命周期
1、生命周期
组件从“生”到“死”的全过程。
每一个组件都有生命周期。
2、生命周期四大阶段
创建阶段:beforeCreate、created
挂载阶段:beforeMount、mounted
更新阶段:beforeUpdate、updated
销毁阶段:beforeDestroy、destroyed
3、生命周期图示
用人的一生来看生命周期:
beforeCreate:出生之前
created:出生了
beforeMount:到派出所办户口(生成虚拟DOM)
mounted:户口本上加了一页纸
......一岁一岁长大......
beforeDestroy:上帝召唤了
destroyed:G了,要重开了
(1)Init Events & Lifecycle
环境初始化,钩子函数、methods选项声明。
(2)Init injections & reactivity
组件上下文数据的注入,对data调用遍历,把data中所有的数据放在this中。
Vue的响应式劫持,就发生在这儿。加set、get钩子。
(3)Has "el" option?
组件有没有el选项。如果没有找mount()方法。
(4)Has "template" option?
找视图结构。视图模板。
(5)如果有template或者如果没有template
YES:Compile template into render function
编译这个模板,变成render方法。render方法用来生成虚拟DOM。
NO:Compile el's outerHTML as template
取当前el节点外部的HTML标签来做。
(6)Create vm.$el and replace "el" with it
调用render方法,创建虚拟DOM。并且对模板遍历指令收集,把指令中数据变成真实数据。
(7)when data changes
当data发生变化时。
(8)Virtual DOM re-render and path
再次调用render,生成一个新的虚拟DOM。
现在得到两个虚拟DOM。
循环递归运算,找出两个虚拟DOM的差异(找出最小的脏节点集合),通过一个队列更新,重新渲染DOM。
(9)when vm.$destroy() is called
当虚拟DOM被destroy()方法调用,路由切换的时候,组件会销毁。
(10)Teardown watchers, child components and event listeners
拆卸watchers、子组件,事件处理器解绑。
二、例子代码
<html>
<head><title>生命周期</title></head>
<body><div id="app"><h1 v-text="num"></h1><button @click="add">自增</button></div><script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script><script>const app = new Vue({data() {return {num: 1}},beforeCreate() {console.log('---beforeCreate')},created() {console.log('---created')},beforeMount() {console.log('---beforeMount')},mounted() {console.log('---mounted')},beforeUpdate() {console.log('---beforeUpdate')},updated() {console.log('---updated')},beforeDestroy() {console.log('---beforeDestroy')},destroyed() {console.log('---destroyed')},methods: {add() {console.log('---add')this.num++}}})app.$mount('#app') // 挂载,相当于el选项</script></body>
</html>
说明:
钩子函数挂载在$options下面