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

一、父组件向子组件传值(通过 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);
},
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 因新工作主要负责微信小程序这一块,最近的重心就移到这一块,该博客是对微信小程序整体的整理归纳以及标明一些细节点,初...
    majun00阅读 7,389评论 0 9
  • 首先 vue 组件化的一个框架。既然是组件化。那么一定存在组件和组件之间传值的问题 在讨论组件和组件怎么传值的问题...
    人话博客阅读 1,173评论 0 50
  • 微信小程序父组件往子组件传值:父:<getCode phone="{{phone}}" bind:myevent=...
    Gaochengxin阅读 4,325评论 0 1
  • 梅归柳欲还,年光等闲离别。晓色料峭尚欺人,寒空近夜,支离余寥落。 须臾年轮众人添,万木渐岑蔚。那堪过往轸念,却待天...
    LinkinPark_9100阅读 154评论 0 1
  • 表哥,带着许多东西看了我妈。我真的很感激。知道这些年,我们没有认真交往。但是从小哪种亲情,已经深深地印在我的脑...
    咫尺为邻阅读 164评论 0 0