properties是小程序的对外属性,接收父组件传过来的属性值。
父传子简单实例:
//comp1.js中
Component({
//声明有一个num变量,是从父组件来的
properties:{
num:{
type:Number,
value:"默认值"
}
}
})
//comp1.json
{
"usingComponents": {},
"component":true//区分是组件还是普通页面
}
//comp1.wxml
<text>第一个组件</text>
<view>{{num}}</view>//显示父组件传来的数据
//exe.js
data:{
FatherData:20
}
//exe.json
{
"usingComponents": {
"my-comp1":"/component/comp1/comp1"//定义组件名
}
}
//exe.wxml
<!-- 父传子 -->
<my-comp1 num="{{fathernum}}"></my-comp1>
结果如下:
子传父,改变父组件数值:
methods:组件方法,包括事件响应函数和任意的自定义方法
//comp1.js
Component{
methods:{//子传父的方法
ChanNum(){
console.log("点击子了组件的按钮");
//修改fathernum传过来的值
this.triggerEvent("fn",10)
}
}
}
//comp1.wxml
<button bindtap="ChanNum">按钮</button>
bind:fn="函数名",当子组件触发事件时,函数触发
//exe.js
chanFatherNum(val){
//console.log(val.detail)
//修改fathernum数据
this.setData({
fathernum:this.data.fathernum+val.detail
})
},
//exe.wxml
<!-- 自定义事件 -->
<my-comp1 num="{{fathernum}}" bind:fn="chanFatherNum"></my-comp1>
现象:点击按钮一次数据+10