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

拼搏现实的明天。 2023-03-04 15:28 90阅读 0赞

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

父组件

json

  1. {
  2. "usingComponents": {
  3. "reply": "../../components/reply/reply"
  4. }
  5. }

html

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

子组件

js

  1. /**
  2. * 组件的属性列表
  3. */
  4. properties: {
  5. commentCount: {
  6. type: Number,
  7. value: 0,
  8. },
  9. commentItem: {
  10. type: Object,
  11. value: ''
  12. }
  13. },

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

  1. /**
  2. * 组件挂载后执行
  3. */
  4. onLoad() {
  5. // 判断评论内容是否为空
  6. if (this.data.commentCount > 0) {
  7. this.setData({
  8. isCommentEmpty: false
  9. });
  10. } else {
  11. this.setData({
  12. isCommentEmpty: true
  13. });
  14. }
  15. },

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

子组件

html

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

js

  1. /**
  2. * 组件的方法列表
  3. */
  4. methods: {
  5. // 点击评论按钮
  6. twoLevelCommentBtnClick: function (e) {
  7. let authorName = e.currentTarget.dataset.authorName;
  8. this.triggerEvent("twoLevelCommentBtn", authorName);
  9. },
  10. },

父组件

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

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

js

  1. // 二级评论按钮点击
  2. twoLevelCommentBtnClick (e) {
  3. this.setData({
  4. placeholderInput: e.detail
  5. });
  6. consoleUtil.log("点击二级评论按钮:" + e.detail);
  7. },

发表评论

表情:
评论列表 (有 0 条评论,90人围观)

还没有评论,来说两句吧...

相关阅读