微信小程序 - 父子组件之间的传值

  在做项目过程中,我们会把多个相同的模块做成一个组件,然后供多个页面一起使用,这样可以实现组件复用。下面我来说说如何实现小程序中的父子组件之间的传值。

1、父组件向子组件传值

  子组件是通过 properties 来接收父组件传递过来的值

例子:

(1)子组件
  1)wxml文件

<!--wxml文件--> <!--components/button/button.wxml-->

<view class="button-con {{type}}">
  <view class='btn-text'>{{desc}}</view>
</view>

  2)js文件(通过 properties 接收父组件传递过来的值)

// components/button/button.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    type:String,
    desc:String,
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {

  },
})

(2)父组件
  1)在json文件中引入子组件(将 component 设置为true,在 usingComponents 中引入对应的子组件)

{
  "component": true,
  "usingComponents": {
    "cus-button":"../button/button"
  }
}

  2)wxml文件

<view class="body_bottom">
   <cus-button class="btn_bom" type="empty" desc="{{btnvalue[0]}}" bindtap="close"></cus-button>
   <cus-button class="btn_bom" type="primary88" desc="{{btnvalue[1]}}" bindtap="ok"></cus-button>
 </view>

(3)如果在一个子组件中引入另一个子组件,对应的方法直接写在methods中

// components/dialog/dialog.js
Component({
  /**
   * 组件的属性列表
   */
  properties: { },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    close(){
      console.log('子组件关闭弹出啦');
      this.triggerEvent('close');
    },
    ok(){
      this.triggerEvent('ok');
    }
  },
  created(){
    console.log(this.data);
  }
})

2、子组件向父组件传值

  子组件通过 triggerEvent 方法向父组件传值

例子:

(1)子组件
  1)wxml文件:

<view class="body_bottom" bindtap="cancel">取消</view>
<view class="body_bottom" bindtap="comfire">确定</view>

  2)js文件:

Component({
  /**
   * 组件的属性列表
   */
  properties: {},

  /**
   * 组件的初始数据
   */
  data: {
      desc:'关闭'  
  },

  /**
   * 组件的方法列表
   */
  methods: {
    cancel(){
      // 不带参数的
      this.triggerEvent('cancel');  
    },
    comfire(){
      // 带参数的
      this.triggerEvent('close',this.data.desc);
    }
  }
})

(2)父组件
  1)现在json文件中引入这个组件,然后在wxml文件中这样写:

 <cu-button class="btn_bom"  bindcancel="cancel"></cu-button>
 <cu-button class="btn_bom"  bindcomfire="comfire"></cu-button>

  2)js文件:

Page({
  cancel: function(){
    console.log('取消')
  },
  comfire: function(e){
     // e.detail 自定义组件触发事件时提供的detail对象
     console.log('确认',e.detail)
  }
})

发布了44 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/LiaoFengJi/article/details/100917675
今日推荐