官网生命周期图

Vue实例的生命周期:
挂载阶段:
- new Vue()调用构造函数
- 初始化生命周期钩子函数
- 调用this.beforeCreate钩子函数
- 监听数据、初始化方法、调用计算属性产生依赖数据
- 调用this.created钩子函数
- 判断有没有设置el属性 (如果没有el等待vm. m o u n t ( ′ C S S 选 择 器 ′ ) ) 如 果 设 置 过 e l 属 性 或 者 调 用 mount('CSS选择器')) 如果设置过el属性或者调用 mount(′CSS选择器′))如果设置过el属性或者调用mount方法,则继续,否则结束了生命过程
- 判断是否有template属性
- 如果有,则template指定的视图为模版
- 如果没有,则以el或$mount指定的节点的outerHTML为视图模版
- 编译模版
- 调用this.beforeMount钩子函数
- 将编译的模版挂载到真实的DOM上
- 调用this.mounted钩子函数,在mounted钩子函数中一般进行DOM的初始化
更新阶段:
- 数据发生变化
- setter方法
- 通知watcher
- 回调this.beforeUpdate钩子函数
- 触发虚拟DOM(re-render)
- 更新真实DOM
- 回调this.updated钩子函数
销毁阶段:
- 主动销毁(调用vm.$destroy())或被动销毁
- 销毁前会调用this.beforeDestroy();
- 销毁
- 销毁后调用this.destroyed()
<!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>Document</title>
</head>
<body>
<div id="app">
<input type="text" v-model="msg">
<p id="box">{{msg}}</p>
<button @click="change">按钮</button>
</div>
<script src="./vue.js"></script>
<script>
var vm=new Vue({
// el:"#app",
// template:"<div id='box'><h1>{{msg}}</h1></div>", //定义当前Vue实例所解析的视图模版
data:{
msg:'hello',
provs:"11111"
},
methods:{
show(){
console.log('show....');
},
change(){
this.provs=2222222+Math.random();
console.log(this.provs);
}
},
computed:{
newMsg(){
return this.msg+',zhangsan';
}
},
//生命周期钩子函数:在Vue创建过程中会被自动回调函数
beforeCreate() {
console.log('breforeCreate...',this.msg,this.show,this.newMsg);//当前Vue实例对象
},
created() {
console.log('created...',this.msg,this.show,this.newMsg);//当前Vue实例对象
},
beforeMount() {
console.log('beforeMount....',this.$el);
},
mounted() {
console.log('mounted....',this.$el);
},
beforeUpdate() {
console.log('beforeUpdate....',this.msg)
},
updated() {
console.log('updated....',this.msg)
},
beforeDestroy() {
console.log('beforeDestroy....')
},
destroyed() {
console.log('destroyed.....')
},
});
vm.$mount("#app") //替代el属性,指定Vue实例挂载的节点
</script>
</body>
</html>