微信小程序-动态添加、删除指定View

一、实现效果:

 二、实现代码:

1).wxml页面:

  • 循环的addPrice是一个数组;
  • 需要保存数组的下标和字段名称;
   <view class="price-detail" wx:for="{{addPrice}}" wx:key="">
      <view class="price-detail-descp">
        <image src="{{hosts}}/images/jianhao.png" class="jianhao" data-index="{{index}}" bindtap='deletePrice'></image>
        <view class="descp-text" >费用描述</view>
        <view class="descp-value">
          <input type="text" name="Price_Name" class="desc-input"  data-index="{{index}}" data-tag="Price_Name" bindblur='setInputValue' placeholder='请输入费用描述' value=""/>
        </view>
      </view>
      <view class="price-detail-num">
        <view class="descp-text">人数限制</view>
        <view class="descp-value">
          <input type="text" name="NumLimit" class="desc-input"  placeholder='请输入人数' data-tag="NumLimit" data-index="{{index}}" bindblur='setInputValue' value=""/>
        </view>
      </view>
      <view class="price-detail-value">
        <view class="descp-text">人均金额</view>
        <view class="descp-value">
          <input type="text" name="Price" class="desc-input" style="color:#888888;" placeholder='限50000元' data-tag="Price" data-index="{{index}}" bindblur='setInputValue' value=""/>
        </view>
      </view>
    </view>
    <view class="addButton" data-index="{{index}}" bindtap='addNewPrice'>+新增收费项目</view>

2).js页面

  • 获取下标
  • 获取要修改的字段名
  • 重新赋值
  • concat() 方法:用于连接两个或多个数组。
data:{
//初始化数组
 addPrice: [{
      Price_Name: "",
      NumLimit: "",
      Price: ""
    }],
}

/**新增** */
  addNewPrice: function() {
    let newArray = {
      Price_Name: "",
      NumLimit: "",
      Price: ""
    }
    this.setData({
      addPrice: this.data.addPrice.concat(newArray)
    })
},

/****删除*/
  deletePrice: function(e) {
    let that = this
    let index = e.target.dataset.index //数组下标
    let arrayLength = that.data.addPrice.length //数组长度
    let newArray = []
    if (arrayLength > 1) {
      //数组长度>1 才能删除
      for (let i = 0; i < arrayLength; i++) {
        if (i !== index) {
          newArray.push(that.data.addPrice[i])
        }
      }
      that.setData({
        addPrice: newArray
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '必须设置一个收费项目',
      })
    }
  },


/**获取输入框信息**/
  setInputValue: function(e) {
    let index = e.target.dataset.index //数组下标
    let tag = e.target.dataset.tag  //字段名称
    let array = this.data.addPrice;
    array[index][tag] = e.detail.value  //赋值
    this.setData({
      addPrice: array
    })
  },

3)保存的数据格式

  • 11
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值