小程序components的生命周期

在components中的生命周期与小程序的生命周期是不一样的,其生命周期函数有两种形式,除了写在外面,还可以统一写在lifetimes属性中

components中的生命周期函数

1、 组件实例化: created 节点树还未导入, 无法使用setData
2、节点树导入完成: attached 可以使用setData来初始化数据,但无法操作节点
3、组件布局完成: ready 组件布局完成,可以获取到节点信息也可以操作节点
4、组件实例被移动到节点树另一个位置: moved
5、组件实例从页面节点移除: detached


生命周期函数的不同写法

   Component({
        properties:{
            innerText:{
                type:String
            }
        },
        data:{

        },
        methods:{

        },
        created:function(){
            // 组件生命周期函数,在组件实例进入页面节点树时执行,注意此时不能调用setData
            console.log('Component-1 >> created');
        },
        attached:function(){
            // 组件生命周期函数,在组件实例进入页面节点树时执行。
            console.log('Component-1 >> attached');
        },
        ready:function(){
            // 在组件布局完成后执行,此时可以获取节点信息
            console.log('Component-1 >> ready');
        },
        moved:function(){
            // 在组件实例被移动到节点树另一个位置时执行
            console.log('Component-1 >> moved');
        },
        detached:function(){
            // 在组件实例被从页面节点树移除时执行
            console.log('Component-1 >> detached');
        },
        lifetimes:{
            // 组件生命周期声明对象,将组件的生命周期收归到该字段进行声明,
            //原有声明方式仍旧有效,如同时存在两种声明方式,则lifetimes字段内声明方式优先级最高
            created:function(){
                console.log('Component-1 lifetimes >> created');
            },
            attached:function(){
                console.log('Component-1 lifetimes >> attached');
            },
            ready:function(){
                console.log('Component-1 lifetimes >> ready');
            },
            moved:function(){
                console.log('Component-1 lifetimes >> moved');
            },
            detached:function(){
                console.log('Component-1 lifetimes >> detached');
            }
        },
        pageLifetimes:{
            // 组件所在页面的生命周期声明对象,目前仅支持页面的show和hide两个生命周期
            show:function(){
                console.log('Component-1 pageLifetimes >> Show');
            },
            hide:function(){
                console.log('Component-1 pageLifetimes >> Hide');
            }
        }

    })

lifetimes中的生命周期函数执行了,外层的生命周期函数没有执行,所有当两者同时存在时,lifetimes中的优先级要高。


小程序从启动到关闭,生命周期函数的执行情况

1、初次打开: 会执行小程序的生命周期钩子函数:onLaunch -> onShow -> onReady
2、使用navigateTo离开当前页面: 保留所离开的页面,执行onHide
3、使用navigateBack离开当前页面: 销毁当前页面,执行onHide -> onUnload
4、使用switchTabTo离开当前页面: 销毁所有非tab页面,但保留所有已经加载的tab页面

原作链接:https://www.jianshu.com/p/1e3b5b507771

你可能感兴趣的:(小程序)