美文网首页vue传值vue钩子函数
Vue生命周期的各个钩子函数

Vue生命周期的各个钩子函数

作者: luckySnail | 来源:发表于2017-04-23 00:08 被阅读382次

    测试生命周期钩子函数代码:

    main.js

    const v= new Vue({

    data: {

    hh:'数据',

    arr: [1,2,3]

    },

    beforeCreate:function() {

    console.log('beforeCreate******',this.hh,this.$el)

    },

    created:function() {

    console.log('created:li的个数******',document.querySelectorAll('li').length)

    console.log('created******',this.hh,this.$el)

    setTimeout(() => {

    this.arr= [6,7,8,9]

    },0)

    },

    beforeMount:function() {

    console.log('beforeMount:li的个数******',document.querySelectorAll('li').length)

    console.log('beforeMount******',this.hh,this.$el)

    },

    mounted:function() {

    console.log('mounted:li的个数******',document.querySelectorAll('li').length)

    console.log('mounted******',this.hh,this.$el)

    },

    beforeUpdate:function() {

    console.log('beforeUpdate:li的个数******',document.querySelectorAll('li').length)

    console.log('beforeUpdate******',this.hh,this.$el)

    },

    updated:function() {

    console.log('updated:li的个数******',document.querySelectorAll('li').length)

    console.log('updated******',this.hh,this.$el)

    },

    beforeDestroy:function() {

    console.log('beforeDestroy******',this.hh,this.$el)

    },

    destroyed:function() {

    console.log('destroyed******',this.hh,this.$el)

    }

    }).$mount('#app')

    // v.$destroy()

    export default v

    index.html:

    结果:

    个人理解总结如下:

    beforeCreated:创建前状态。在实例初始化之后,数据观测(data observer) 和 event/watcher 事件配置之前被调用。[此时数据,计算属性,绑定方法,watcher 都读不到]

    created:实例创建完成状态,可以调用实例的数据,方法。还未挂载,所以el是undefined。[此阶段可以用来初始化缓存数据]

    beforeMonted: 挂载钩子,即将挂载,找挂载节点, 如果设定了el元素,那Vue实例一切操作只对这个根目录和他的子元素生效。这个阶段生成的是虚拟 Dom。

    monted:挂载完成,dom渲染到了页面中。此步可以用来操作获取后台数据。(实际项目中也曾在created状态时用来异步获取后台数据,暂时不清楚最好是在哪一步进行此操作)

    update:数据更新。数据更新和真正渲染到Dom中是有时间差的因为是事件队列。[尽量避免在此阶段更改状态可能会导致无限循环。]

    beforeDestroy:实例销毁之前调用,在这一步,实例还是可用的。

    destoryed:实例销毁。解绑掉了所有数据,绑定方法,watcher,子实例等

    以上测试代码可从github上拉取测试:github拉取地址

    之前看到一个描述比较详细的文章,下图是博主对生命周期的标注,清晰明了,对vue感兴趣的朋友可以看看。链接是这个文章链接

    昨天自己又画了一遍流程如下:

    不知道理解的对不对,如有问题请各位指教。

    相关文章

      网友评论

        本文标题:Vue生命周期的各个钩子函数

        本文链接:https://www.haomeiwen.com/subject/wpaszttx.html