生命周期-->生命周期钩子函数:一个组件从创建到销毁的一个过程就是生命周期
beforeCreate:创建前
1、组件创建会执行的一个生命周期函数,我们可以在当前生命周期中创建一个loading.当页面加载完成的时候讲loading移除
2、在当前生命周期函数中是访问不到其他生命周期函数以及data身上的属性
created:创建后(重)
1、当create生命周期函数执行的时候,会将data以及methods身上所有的属性和方法添加到vm的实例身上
2、created执行的时候会遍历data身上所有的属性,给这些属性添加一个getter/setter方法
3、我们可以在当前生命周期函数中进行前后端数据的请求(发起ajax)
beforeMount 挂载前
1、当前生命周期函数可以对data中的数据做最后的修改
2、如果在当前生命周期函数中添加的属性是没有getter和setter方法的。如果需要拥有的情况则用$set
3、当前生命周期函数中是模板和数据还未进行结合
mounted: 挂载后(重)
1、当前生命周期函数是数据和模板进行相结合,生成了真正的DOM结构
2、在当前生命周期函数重我们可以访问到真实的DOM结构
3、我们可以在当期生命周期函数中做一些插件的实例化(Swiper better-scroll echarts....)
ref:
定义: ref="名称"(名称必须是当前组件中独一无二的)
获取: this.$refs.名称
beforeDestroy: 销毁前(重)
1、在当前生命周期函数中我们依旧是可以访问到真实的DOM结构,因此我们可以在当前生命周期函数中做
事件的解绑,以及监听的移除等操作
destroyed:销毁后
1、当前生命周期函数执行的时候会将vm与模板之间的关联进行断开
2、在当前生命周期函数中我们无法通过ref来访问到真实的DOM结构了
beforeUpdate:更新前 (多次执行)
1、当数据更新前会执行的生命周期函数
2、当前生命周期是更新的数据还未和模板进行相结合,因此我们可以在当期生命周期函数中做更新数据的最后修改
updated:更新后 (多次执行)
1、当前函数是更新的数据和模板进行了相结合。
2、我们可以在当前生命周期函数中获取到数据更新后最新的DOM结构
3、我们一般情况下会在这里做插件的实例化,但是需要条件的判断。如果不加判断的情况下会非常耗费性能
<!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"> <h2 ref="h2" id="box">{{msg}}</h2> <h2>{{obj.age}}</h2> <button @click="handleUpdate">数据更新</button> </div> <button onclick="handleDestroy()">销毁</button> </body> </html> <script src="vue.js"></script> <script> var vm = new Vue({ el:"#app", beforeCreate(){ console.log("beforeCreate----"); console.log(this.msg) console.log(this) }, created(){ console.log("created-----") }, data:{ msg:"1905", obj:{} }, methods:{ handleUpdate(){ this.msg = "1902"; // console.log(this.msg); // console.log(1); this.$nextTick(()=>{ console.log(document.getElementById("box").innerText); }) } }, beforeMount(){ console.log("beforeMount----"); // this.msg = "1902"; // this.age = 20; this.$set(this.obj,"age",20) console.log(document.getElementById("app").innerHTML) }, mounted(){ console.log("mounted----") console.log(document.getElementById("app").innerHTML) console.log(this.$refs.h2); }, beforeUpdate(){ console.log("beforeUpdate ---") console.log(document.getElementById("app").innerHTML) this.msg = "不让你变成1902"; }, updated(){ console.log("updated ---") // if(!this.swiper){ // this.swiper = new Swiper(); // } }, beforeDestroy(){ console.log("beforeDestroy----") console.log(document.getElementById("app").innerHTML) console.log(this.$refs.h2); }, destroyed(){ console.log("destroyed") console.log(document.getElementById("app").innerHTML) console.log(this.$refs.h2); } }) function handleDestroy() { vm.$destroy(); } /* $nextTick():获取数据更新后最新的DOM结构 面试题: nextTicke是同步的还是异步的? 同步的 而nextTick中的函数是 异步的 我可以在当前函数中获取到数据更新后最新的DOM结构 如何获取到数据更新后最新的DOM结构 1、nextTick (底层原理类似一个setTimeout 时间为20ms) 2、wacth 3、updated */ </script>