微信小程序Component组件

1.wxml

定义了一个循环遍历的<view>,并绑定了一个点击方法

<view class="confession-container">
  <view wx:for="{{confessions}}" wx:key="index" class="confession-item" bindtap="onTapConfession" data-id="{{item.id}}">
    <view class="confession-title">{{item.title}}</view>
    <view class="confession-content">{{item.content}}</view>
  </view>
</view>

2.wxss

.confession-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 20rpx;
}

.confession-item {
  width: calc(50% - 20rpx);
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  box-sizing: border-box;
}

.confession-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.confession-content {
  font-size: 14px;
  color: #666666;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  word-break: break-all;
}

.confession-item:hover {
  background-color: #ebebeb;
}

3.js

定义了需要传递的数据,以及点击方法

Component({
  properties: {
    confessions: {
      type: Array,
      value: []
    }
  },
  methods: {
    // 点击某个表白的回调函数
    onTapConfession(event) {
      const confessionId = event.currentTarget.dataset.id;
      // 在这里可以进行相应的处理,比如跳转到表白详情页面
      console.log("点击了表白,ID为:" + confessionId);
    }
  }
})

4.引用页面json/app.json

左边的名字可以自己随便命名,此处页面路径要写自己组件的路径

"usingComponents": {
    "com":"/components/myComponent/myComponent"
  }

5.引用页面js

data里是传递的数据,需要和组件里的properties:里的数据一样

Page({
  data: {
    confessions: [
      { id: 1, title: '表白标题1', content: '表白内容1' },
      { id: 2, title: '表白标题2', content: '表白内容2' },
      // 添加更多表白对象...
    ]
  }
})

6.引用页面wxml

传递数据

<com  confessions="{{confessions}}"></com>

7.参考图

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值