您当前的位置: 首页 >  微信小程序

彭世瑜

暂无认证

  • 3浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

微信小程序:页面Page和组件Component生命周期执行的先后顺序

彭世瑜 发布时间:2021-10-14 17:45:52 ,浏览量:3

Vue.js和小程序生命周期

  • Vue.js:页面Page和组件Component生命周期执行的先后顺序

  • 微信小程序:页面Page和组件Component生命周期执行的先后顺序

在这里插入图片描述

组件

// components/test-component/test-component.js
Component({
  /**
   * 组件生命周期函数-在组件实例刚刚被创建时执行
   */
  created() {
    // 注意此时不能调用 setData
    console.log('Component created');
  },

  /**
   * 组件生命周期函数-在组件实例进入页面节点树时执行
   */
  attached() {
    console.log('Component attached');
  },

  /**
   * 组件生命周期函数-在组件布局完成后执行
   */
  ready() {
    console.log('Component ready');
  },
  
  /**
   * 组件生命周期函数-在组件实例被移动到节点树另一个位置时执行
   */
  moved() {
    console.log('Component moved');
  },

  /**
   * 组件生命周期函数-在组件实例被从页面节点树移除时执行
   */
  detached() {
    console.log('Component detached');
  },
});


页面

// pages/test-page/test-page.js
Page({
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('Page onLoad');
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log('Page onReady');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('Page onShow');
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('Page onHide');
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('Page onUnload');
  },
});

页面使用组件

{
  "usingComponents": {
    "test-component": "/components/test-component/test-component"
  }
}



控制台输出:

# 显示过程
Component created
Component attached

Page onLoad
Page onShow

Component ready

Page onReady

## 销毁过程
Page onUnload

Component detached

所以,如果页面需要接收到数据(onLoad, onShow),组件需要接收页面传递过来的数据,这时,组件在(ready)阶段才能拿到数据

参考 https://developers.weixin.qq.com/miniprogram/dev/reference/api/Page.html https://developers.weixin.qq.com/miniprogram/dev/reference/api/Component.html

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.2868s