组件生命周期
主要生命周期:created
(刚刚创建好)、attached
(完全初始化完毕进入节点数)、detached
(组件离开页面节点树后)
另外的生命周期:ready
(在组件在视图层布局完成后执行)、moved
(在组件实例被移动到节点树另一个位置时执行)、error
(每当组件方法抛出错误时执行)
Component({
lifetimes: {
attached() {
// 在组件实例进入页面节点树时执行
},
detached() {
// 在组件实例被从页面节点树移除时执行
},
},
// 以下是旧式的定义方式,可以保持对 <2.2.3 版本基础库的兼容
attached() {
// 在组件实例进入页面节点树时执行
},
detached() {
// 在组件实例被从页面节点树移除时执行
},
// ...
})
组件所在页面的生命周期
show
(组件所在的页面被展示时执行)、hide
(组件所在的页面被隐藏时执行)、resize
(组件所在的页面尺寸变化时执行)
代码示例:
Component({
pageLifetimes: {
show() {
// 页面被展示
},
hide() {
// 页面被隐藏
},
resize(size) {
// 页面尺寸变化
}
}
})
自定义组件的关键内容
- 构建自定义组件
- 调用自定义组件
- 传值给自定义组件
- 组件传值出来
实例讲解

功能:红框中3张图片显示品牌下单品部分,点击单品图片跳转对应的品牌详情页面,这块就是用自定义组件拆分做了试验。
home.wxml代码
<goodLists goodLists="{{item}}" ></goodLists>//这个组件刚好在一个循环列表里,这里给自定义组件传值{{item}}
home.json代码
{
"usingComponents": {
"goodLists": "/components/goodLists/goodLists",
}
}
自定义组件代码
<!--components/goodLists.wxml-->
<view scroll-x style="width: 710rpx;height:300rpx;white-space: nowrap; display: flex;align-items:flex-start;flex-direction:row;justify-content:flex-start;overflow:hidden">
<view wx:for="{{goodLists.goodsList}}" bindtap='linkToBrandRush' data-brandid='{{item.brandId}}' data-brandsource='{{item.goodsSource}}'>
<view style="width:218rpx;height:300rpx;margin-right:6rpx" >
<!-- <view>{{goodLists}}</view> -->
<image src="{{item.goodsImages[0]}}" style='width:218rpx;height:218rpx;' mode="aspectFit"></image>
<view style='font-size:26rpx;text-align:center'>¥{{item.salePrice}}</view>
<view style='font-size:22rpx;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;color:#db9548;text-align:center'>VIP省/赚{{item.commissionMoney}}元</view>
</view>
</view>
</view>
<!--components/goodLists.json-->
{
"component": true,
"usingComponents": {}
}
// components/goodLists/goodLists.js
var app = getApp()
Component({
/**
* 组件的属性列表
*/
properties: {
goodLists: {
type: Object,
value: '',
observer: function (newVal, oldVal) {
}
},
/**
* 组件的方法列表
*/
methods: {
linkToBrandRush(event) {
var barndId = event.currentTarget.dataset['brandid'];
var brandSoruce = event.currentTarget.dataset['brandsource'];
wx.navigateTo({
url: '/pages/brandInfo/brandInfo?brandId=' + barndId + "&brandSource=" + brandSoruce
});
}
}
})
网友评论