微信小程序循环动态添加删除列表

主要实现微信小程序动态添加删除列表,解决多个相同事件绑定值问题

效果图如下

.wxml

<block wx:for="{{scoreList}}" wx:key>
  <view class="cu-bar bg-white solid-bottom margin-top">
    <view class="action">
      <text class="cuIcon-title text-brown"></text> 第{{item.num}}节
    </view>
  </view>
  <view class="cu-form-group">
    <view class="title">分数</view>
    <picker bindchange="scoreChange" value="{{item.score}}" data-num="{{item.num}}" range="{{scoreArr}}">
      <view class="picker">
        {{item.score?scoreArr[item.score]:'请选择'}}
      </view>
    </picker>
  </view>
</block>
<view class="padding flex flex-wrap justify-between align-center">
  <button class="cu-btn bg-gradual-pink cuIcon-add" bindtap="objectAdd">增加</button>
  <button class="cu-btn bg-gradual-pink cuIcon-move" bindtap="objectMove">减少</button>
</view>
.js
 Page({
   data: {
     scoreList: [], //分数数组
     scoreArr: ["0分", "1分", "2分", "3分", "4分", "5分"],
     num: 0,
   },
   scoreChange(e) {
     var that = this;
     var tempList = that.data.scoreList;
     for (var i = 0; i < tempList.length; i++) {
       //找到所选的下拉框赋值
       if (tempList[i]["num"] == e.currentTarget.dataset.num) {
         tempList[i]["score"] = e.detail.value;
         break;
       }
     }
     //改变后的值赋值scoreList重新绑定
     that.setData({
       scoreList: tempList
     })
     console.log('scoreList=' + JSON.stringify(that.data.scoreList)) //最终提交到后台得到数据
   },
   //添加一个列表
   objectAdd(e) {
     var that = this
     var addlist = this.data.scoreList;
     var obj = {
       score: null,
       num: this.data.num + 1
     }
     addlist.push(obj)
     this.setData({
       scoreList: addlist,
       num: this.data.num + 1
     })
   },
   //减少一个列表 从最后一个开始减少
   objectMove(e) {
     if (this.data.scoreList.length > 0) {
       this.data.scoreList.splice(this.data.scoreList.length - 1, 1);
       this.setData({
         scoreList: this.data.scoreList,
         num: this.data.num - 1,
       })
     }
   }
 })
 

猜你喜欢

转载自www.cnblogs.com/yejiao/p/11389509.html