如何自定义组件?
1.新建Component
. 与Page
类似,包含四件套.
2.在.json
中编写组件声明:
{
"component": true
}
3.编写组件基础的wxml
/ wxss
4.在普通页面中,引入该组件,使用该组件.
{
"usingComponents": {
"mybutton": "path/to/the/custom/component"
}
}
<mybutton></mybutton>
如何自定义组件的属性?
1.在组件的js
中声明属性:
// components/mybutton/mybutton.js
Component({
/** 声明组件的属性列表 */
properties: {
round: {
type: Boolean,
value: false
},
color: {
type: String,
value: '#36D'
},
value: {
type: String,
value: '默认按钮'
}
}
})
2.在组件的wxml
中使用属性:
<!--components/mybutton/mybutton.wxml-->
<view class="mbutton {{round?'round':'rect'}}"
style="background-color: {{color}};">
{{value}}
</view>
3.在使用组件时, 为组件指定属性:
<my-button value="去往购物车" color="#f42211" round>
</my-button>
如何自定义组件的事件?
1.在组件的js
中定义触发事件的条件:
// components/mybutton/mybutton.js
Component({
/**
* 组件的初始数据
*/
data: {
lastTime : 0 // 记录上次单击时的时间毫秒值
},
/** 组件的方法列表 */
methods: {
tapEvent(){
// 捕获到单击事件 判断距离上次单击多长时间
let now = new Date().getTime() // 毫秒
if(now - this.data.lastTime<350){
// 触发了双击场景 触发父组件定义的doubletap
this.triggerEvent('doubletap')
now = 0
}
this.data.lastTime = now // 重写lastTime时间
}
}
})
当达到了事件触发条件, 调用this.triggerEvent('doubletap')
触发事件.
2.在父组件中, 绑定自定义事件doubletap:
<my-button bind:doubletap="doubleTapEvent"></my-button>