组件的生命周期:
生命周期是指一个组件从创建运行到销毁的整个阶段,强调的是一个时间段。
生命周期函数:是由vue框架提供的内置函数,会伴随着组件的生命周期,自动按次序执行。
第一阶段.组件创建阶段:
beforecCreated--->created--->beforeMount--->mounted
第二阶段.组件运行阶段
beforeUpdated--->updated
第三阶段.组件销毁阶段
beforeDestroyed--->destroyed
一组件创建阶段:
created阶段:组件的props/data/methods已经创建好,都处于可用状态。
但是组件的模板结构还未渲染好,在此时间可发起Ajax请求来拿数据。
并且把请求到的数据,转存到data中,供template模板渲染使用methods:{ show(){ console.log('调用了test组件中的show方法') }, initBookList(){ const xhr=new XMLHttpRequest() xhr.addEventListener('load',()=>{ const result=JSON.parse(xhr.responseText) console.log(result) this.books=result.data }) xhr.open('get','http://www.liulongbin.top:3006/api/getbooks') xhr.send() } }, created(){//组件的props/data/methods已经创建好,都处于可用状态。 //但是组件的模板结构还未渲染好,在此时间可发起Ajax请求来拿数据。 //并且把请求到的数据,转存到data中,供template模板渲染使用 this.show() this.initBookList() } //运行结果: //{status: 200, msg: '获取图书列表成功', data: Array(3)}
beforeMount:将要把内存中编译好的html结构渲染到浏览器内,此时浏览器还没有当前组件的dom结构,基本没什么意义。
<h1 id="myh1">test.vue组件-------{{ books.length }}本图书</h1> beforeMount(){ console.log(this.$el)//undefined const dom=document.querySelector('#myh1') console.log(dom)//test.vue?dc1f:41 null }
mounted:已经把dom中的html结构渲染到浏览器中。
mounted(){ console.log(this.$el)//<div>...</div> const dom=document.querySelector('#myh1') console.log(dom)//<h1 id='myh1'>...</h1> }
二组件运行阶段 (最少执行0次,最多执行n次)
beforeUpdate:修改数据时,会调用beforeUpdate,将要根据变化过后最新的数据,重新渲染组建的模板结构。
beforeUpdate(){ console.log(this.message) const dom=document.querySelector('#pppp') console.log(dom.innerHTML) } //第一次:message的值是hello vue.js // hello vue.js! //第二次: message的值是hello vue.js! // hello vue.js!!
updated:已经根据最新的数据,完成了组件dom结构的重新渲染。想要操作最新的dom,必须把代码写道update中
updated(){ console.log(this.message) const dom=document.querySelector('#pppp') console.log(dom.innerHTML) } //hello vue.js!! //test.vue?dc1f:56 message的值是hello vue.js!!
三组件销毁阶段
beforeDestroy:将要销毁此组件但还未销毁
destroyed:组件已经被销毁,此组件在浏览器中对应的dom结构已经被完全移除。