简单组件微信小程序实例

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值