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

2019-01-08  本文已影响0人  异想天不开_9950

一、父组件向子组件传值(通过 properties 属性)

json

{
  "usingComponents": {
    "reply": "../../components/reply/reply"
  }
}

html

<!-- 评论回复 -->
<reply commentCount='{{commentList.length}}' commentAvatarUrl='{{commentAvatarUrl}}' bind:oneLevelComment='oneLevelCommentSend'></reply>

js

/**
 * 组件的属性列表
 */
properties: {
  commentCount: {
    type: Number,
    value: 0,
  },
  commentItem: {
    type: Object,
    value: ''
  }
},

然后,在子组件方法中通过 this.data.commentCount 来获取数值

/**
 * 组件挂载后执行
 */
ready: function () {

  // 判断评论内容是否为空
  if (this.data.commentCount > 0) {
    this.setData({
      isCommentEmpty: false
    });
  } else {
    this.setData({
      isCommentEmpty: true
    });
  }
},

二、子组件向父组件传值(通过 triggerEvent 事件)

需要手动触发获取

html

<image class='comment-comment' src='../../images/comment_comment.png' bindtap='twoLevelCommentBtnClick' data-author-name="{{commentItem.AuthorName}}"></image>

js

/**
 * 组件的方法列表
 */
methods: {
  // 点击评论按钮
  twoLevelCommentBtnClick: function (e) {
    let authorName = e.currentTarget.dataset.authorName;
    this.triggerEvent("twoLevelCommentBtn", authorName);
  },
},

html
通过 bind:twoLevelCommentBtn='twoLevelCommentBtnClick' 把子组件的事件传递给父组件的自定义事件

<!-- 评论内容 -->
<block wx:for="{{commentList}}" wx:key="{{index}}">
  <comment commentCount='{{commentList.length}}' commentItem='{{item}}' bind:twoLevelCommentBtn='twoLevelCommentBtnClick' bind:twoLevelCommentCell='twoLevelCommentCellClick'></comment>
</block>

js

// 二级评论按钮点击
twoLevelCommentBtnClick (e) {
  this.setData({
    placeholderInput: e.detail
  });
  consoleUtil.log("点击二级评论按钮:" + e.detail);
},
上一篇 下一篇

猜你喜欢

热点阅读