首先在根目录找到components文件夹,没有就新建
01.png
然后在components目录下新建目录用于放组件代码 这里对目录命名auditPop
对auditPop右键新建component,然后输入自己要自定义的组件名字auditPop,这时会生成四个文件 auditPop.js,auditPop.wxml,auditPop.json,auditPop.wxss;
auditPop.json 里需要配置为该部分代码为组件
{
"component": true,
"usingComponents": {}
}
auditPop.wxml 和auditPop.wxss是组件的外在表现,这里就不贴了。
auditPop.js里会自动生成三个对象:properties,data,methods
Component({
/**组件的属性列表*/
properties: {
//组件的属性,在wxml里引用组件时可以直接赋值
itemId: {
type: String,
value: ''
}
},
/**组件的初始数据*/
data: {
//用于初始化一些数据,如组件弹窗标题,字体颜色的什么的
flag:true
},
/** 组件的方法列表*/
methods: {
//隐藏弹框
hidePopup: function() {
this.setData({
flag: !this.data.flag
})
},
//展示弹框
showPopup() {
this.setData({
flag: !this.data.flag
})
},
//组件自定义方法,建议以“_”开头 如:
_success() {
//触发成功回调
this.hidePopup();
this.triggerEvent("success", this.properties.itemId);
},
}
})
在A页面引用方式:
A.wxml
<!-- 下面的bind:success对应的是auditPop.js里method对象下面的_success方法,
itemId对应 auditPop.js里properties 对象的itemId -->
<auditPop id='auditPop' itemId='0' bind:success="forceAuditTap">
</auditPop>
A.json 需要注册声明一下
"usingComponents": {
"auditPop": "/components/auditPop/auditPop"
}
A.js
首先在data里声明auditPop
data: {
auditPop: ''
},
在onLoad方法里赋予意义
onLoad: function(options) {
//这里的#auditPop 对应在A.wxml里的id
this.auditPop = this.selectComponent("#auditPop");
}
最后 在需要的时候调用组件方法,这里是定义的弹窗,因此调用显示的方法
this.auditPop.showPopup();