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

官方文档:https://developers.weixin.qq.com/miniprogram/dev/reference/api/Component.html

正如官方显示组件的生命周期中常用的如下:

image-20230521011534936

!> 组件的生命周期方法编写的位置与页面的生命周期是不一样的,组件生命周期声明是写在 lifetimes 当中

官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/lifetimes.html

示例

监听组件生命周期

// components/c-test/c-test.js
Component({
  // 监听当前组件的生命周期
  lifetimes: {
    created() {
      console.log("created 组件被创建出来了");
    },
    ready() {
      console.log("ready 组件被附加到页面的节点树上了");
    },
    attached() {
      console.log("attached 组件被显示出来了");
    },
    detached() {
      console.log("detached 组件从页面上被移除了");
    },
  }
});

首页页面使用 c-test 组件:

<!--index.wxml-->
<text>首页</text>
<myTest wx:if="{{isShow}}" />
<button bindtap="toggleShow">切换c-test组件显示状态</button>
// index.js
Page({
  data: {
    isShow: true
  },
  toggleShow() {
    this.setData({isShow: !this.isShow})
  }
})
{
  "usingComponents": {
    "myTest": "/components/c-test/c-test"
  }
}

组件当中监听页面生命周期

// components/c-test/c-test.js
Component({
  // 监听当前组件的生命周期
  lifetimes: {
    created() {
      console.log("created 组件被创建出来了");
    },
    ready() {
      console.log("ready 组件被附加到页面的节点树上了");
    },
    attached() {
      console.log("attached 组件被显示出来了");
    },
    detached() {
      console.log("detached 组件从页面上被移除了");
    },
  },
  // 监听挂载到的页面对应的生命周期
  pageLifetimes: {
    hide() {
      console.log("页面被隐藏了");
    },
    show() {
      console.log("页面显示出来了");
    }
  }
});
posted @   BNTang  阅读(116)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示