先放一张官网生命周期图:
vue有8种生命周期函数:
测试代码:
组件模板自己试着写就好,此处贴js代码
(省略部分代码)
export default {data () {return {todos: [],allCounts: 0,filter: 'all',id: 0,states: ['all', 'active', 'completed']}},beforeCreate () {console.log('==============' + 'beforeCreated' + '===================')console.log(this.$el)console.log(this.$data)console.log(this.filter)},created () {console.log('==============' + 'created' + '===================')console.log(this.$el)console.log(this.$data)console.log(this.filter)},beforeMount () {console.log('==============' + 'beforeMount' + '===================')console.log(this.$el)console.log(this.$data)console.log(this.filter)},mounted () {console.log('==============' + 'mounted' + '===================')console.log(this.$el)console.log(this.$data)console.log(this.filter)},beforeUpdate () {console.log('==============' + 'beforeUpdate' + '===================')console.log(this.$el)console.log(this.$data)console.log(this.filter)},updated () {console.log('==============' + 'updated' + '===================')console.log(this.$el)console.log(this.$data)console.log(this.filter)},beforeDestroy () {console.log('==============' + 'beforeDestroy' + '===================')console.log(this.$el)console.log(this.$data)console.log(this.filter)},destroyed () {console.log('==============' + 'destroyed' + '===================')console.log(this.$el)console.log(this.$data)console.log(this.filter)}}
效果:
至于destroyed就不好演示了。
destroyed钩子函数有一点一定要特别注意:在执行destroy方法后,对data的改变不会再触发周期函数,此时的vue实例已经解除了事件监听以及和dom的绑定,但是dom结构依然存在。所以对于实时显示的通知型组件,在他destroyed之前,我们必须手动removeChild()删除该节点;否则,DOM节点还是存在,影响浏览器性能。
还有一点需要补充:
组件套用时生命周期:
父组件:tabs
子组件:tab、tab-container
我的应用场景是:
<tabs><tab /><tab /><tab /><tab-container /></tabs>
/*tabs的打印代码*/beforeMount () {console.log('============Tabs befortemounted==============')},mounted () {console.log('============Tabs mounted==============')},created () {console.log('============Tabs created==============')}/*tab的打印代码*/beforeMount () {console.log('----------------tab beforemounted-------------')},mounted () {this.$parent.panes.push(this)console.log('----------------tab mounted-------------')},created () {console.log('----------------tab created-------------')}/*tab-container的打印代码*/beforeMount () {console.log('!!!!!!!!!!!!!!!!tab container beforemounted!!!!!!!!!!!!!!!!!')},mounted () {console.log('!!!!!!!!!!!!!tab container mounted!!!!!!!!!!!!!!!!!')},created () {console.log('!!!!!!!!!!!!!!!!!!!!!tab container created!!!!!!!!!!!!!!!!!!!!!!!')}
浏览器结果:
结论:先执行父组件的created和beforeMounted函数;再按子组件的使用顺序,执行子组件的created和beforeMounted函数;依旧按照子组件的执行顺序执行mounted函数,最后是父组件的mounted函数;
也就是说父组件准备要挂载还没挂载的时候,子组件先完成挂载,最后父组件再挂载;所以在真正整个大组件挂载完成之前,内部的子组件和父组件之间的数据时可以流通的(好难表达。。。。)
如果觉得《vue生命周期钩子函数详解》对你有帮助,请点赞、收藏,并留下你的观点哦!