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

官方文档: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("页面显示出来了");
    }
  }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值