支付宝小程序父组件和自定义组件传递数据

作者: MJ 分类: 小程序 发布时间: 2019-09-30 23:28

支付宝小程序父子组件相互传递数据

父传子:

[父组件] page/index/index.axml

<component name="我是父组件传递过去的" />

[子组件] components/component/index.axml

<view>
  我是子组件
  {{ name }} // 我是父组件传递过去的
</view>

子传父:

[父组件] pages/index/index.axml

{{ age }} // 39
<component name="我是父组件传递过去的" onShowage="onShowage"></component>

[父组件] pages/index/index.js

Page({
  data:{
    age:0
  },
  onShowage(data){
    this.setData({
      age:data
    });
  }

[子组件] components/component /index.axml

<view>
  我是子组件
  {{ name }}
  <button onTap="changeData">改变data</button> 
</view>

[子组件] components/component/index.js

Component({
  data:{
    age:39
  },
  didMount(){
    this.onShowage();
  },
  didUpdate(){
    this.onShowage();
  },
  methods:{
    onShowage(){
      this.props.onShowage(this.data.age);
    },
    changeData(){
      this.setData({
        age:this.data.age + 1
      });
    }
  }
})

注意:外部使用自定义组件时,如果传递参数是函数,一定要以 on 为前缀,否则会将其处理为字符串。

https://docs.alipay.com/mini/framework/develop-custom-component#props

欢迎关注小程序,感谢您的支持!

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

邮箱地址不会被公开。 必填项已用*标注