微信小程序中的生命周期

一.页面的生命周期

onLoad: 页面加载时触发。
onShow: 页面显示时触发。
onReady: 页面初次渲染完成时触发。
onHide: 页面隐藏时触发。
onUnload: 页面卸载时触发。

onLoad(options): 

触发时机: 页面加载时触发,一般在页面初始化时调用。
参数: options为页面跳转所带来的参数。
用途:
    进行页面初始化操作,例如获取数据。
    解析场景值(scene)等。
 

Page({
  onLoad: function(options) {
    console.log('Page loaded with options:', options);
    // Initialize page data or perform API requests here
  }
});

onShow(): 

触发时机: 页面显示或从后台切换到前台时触发。
用途:
    每次页面显示时需要的操作,例如刷新数据。
    可以用来统计页面展示次数等。
 

Page({
  onShow: function() {
    console.log('Page is now shown');
    // Perform actions every time the page is shown
  }
});

 onReady():

触发时机: 页面初次渲染完成时触发,仅触发一次。
用途:
    页面初次渲染后执行的操作,例如与视图相关的操作,初始化图表等。
 

Page({
  onReady: function() {
    console.log('Page initial rendering completed');
    // Perform operations that require the view to be rendered, such as initializing a canvas
  }
});

onHide():

触发时机: 页面隐藏时触发,例如用户进入其他页面或小程序切入后台。
用途:
    暂停或保存当前页面状态。
    停止定时器,减少资源消耗。
 


Page({
  onHide: function() {
    console.log('Page is now hidden');
    // Pause ongoing tasks or save state
  }
});

onUnload(): 

触发时机: 页面卸载时触发,例如用户关闭当前页面或跳转到其他页面。
用途:
    清理资源,例如停止网络请求、删除定时器等。
    保存用户数据或状态。
 

 


Page({
  onUnload: function() {
    console.log('Page is now unloaded');
    // Clean up resources and save necessary data
  }
});

 总的来说,页面生命周期主要关注整个页面的加载、显示、渲染和卸载过程,而组件生命周期则更关注组件实例的创建、插入、布局、移动和移除等过程。因此,它们在使用和触发时机上有一定的差异。

二.组件的生命周期 

created: 组件实例刚刚被创建时触发。
attached: 组件被插入到页面节点树时触发。
ready: 组件布局完成后触发。
moved: 组件实例被移动到另外一个节点时触发。
detached: 组件实例被从页面节点树移除时触发。 

created(): 

触发时机: 在组件实例刚刚被创建并初始化的时候触发。
用途:
    初始化组件的数据。
    与父组件或其他逻辑建立联系,但此时还不能操作 DOM。
 

Component({
  created() {
    console.log('Component instance created');
    // Initialize component data
  }
});

attached():

触发时机: 组件实例进入页面节点树时触发。
用途:
    可以获取节点信息,进行一些需要 DOM 节点的初始化操作。
 

Component({
  created() {
    console.log('Component instance created');
    // Initialize component data
  }
});

 ready():

 触发时机: 组件布局完成并且可以交互时触发。
用途:
    操作 DOM,进行视图相关的初始化工作,例如绘制图表等。

Component({
  ready() {
    console.log('Component is ready');
    // Perform operations that require the component to be fully rendered
  }
});

 moved():

 触发时机: 当组件实例被移动到别的位置时触发。
用途:
    一般较少用到,主要用于处理组件移动后的逻辑。

Component({
  moved() {
    console.log('Component moved');
    // Handle the component being moved
  }
});

 detached():

触发时机: 组件实例被从页面节点树移除时触发。
用途:
    清理资源,如定时器、事件监听器等。
 


Component({
  detached() {
    console.log('Component detached from the page');
    // Cleanup resources and perform teardown operations
  }
});

 微信小程序中的组件生命周期方法类似于页面生命周期,但也有其独特之处。理解这些生命周期方法有助于在合适的时机执行代码,从而更好地控制组件的行为和状态。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值