微信小程序-组件的生命周期

components中的生命周期函数

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

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

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

生命周期函数的不同写法

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

   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');
            }
        }

    })

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值