您的位置:首页 > 移动开发 > 微信开发

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

2020-06-09 04:43 525 查看

components中的生命周期函数

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

})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: