在微信小程序中,表单需要提交多项数据时,提交的数据如果是每一项都列举出来并赋值的话,代码显得冗余,代码维护性低。如下,在data里新增一个字段age、sex、number,输入时要每个都单独赋值,提交请求时每个都要取一遍;
wx.request({
url: `${url}`,
header: {"Content-Type": "application/x-www-form-urlencoded"},
data:{name:this.data.name,age:this.data.age,sex:this.data.sex},
method:'POST',
success: function (res) {
}
})
此时,如果在该A对象新增两个属性,两个属性一个为要提交的字段名,一个为值(此A对象为如下的inputList,该对象用于页面循环渲染)。
输入的时候传index参数,拼接对应属性进行赋值。
提交时用B对象(此B对象为如下的dataList,用于提交的数据对象),循环该A对象里的对象和值,同时往B对象里新增属性和赋值,是不是让代码更简洁呢?下面就直接上代码吧~
<view id="personal">
<view class="personal-view">
<text class="head">信息提交</text>
<view class="input-view" wx:for="{{inputList}}" wx:key="key">
<view class="text-view">
<text class="required-icon" wx:if="{{item.required}}">*</text>
<text class="input-name">{{item.name}}:</text>
</view>
<input class="input" placeholder="{{item.tip}}" value="{{item.value}}" data-inputindex="{{index}}"
bindinput="changeVal"></input>
</view>
<button class="submit-btn" bindtap="handleSubmit">提交</button>
</view>
</view>
Page({
data: {
/**
* name:标题
* tip:input提示信息
* required:是否为必填项
* type:为提交表单时的字段名称
* value:提交的数据
* tipMsg:为警告信息
* */
inputList: [
{ name: '姓名', tip: '请输入姓名', required: true, type: 'name', value: '', tipMsg: '请输入姓名' },
{ name: '性别', tip: '请输入性别', required: true, type: 'sex', value: '', tipMsg: '请输入性别' },
{ name: '年龄', tip: '请输入年龄', required: false, type: 'age', value: '', tipMsg: '请输入年龄' },
{ name: '手机号码', tip: '请输入手机号码', required: true, type: 'number', value: '', tipMsg: '请填写手机号码' }
],
},
//输入并赋值
changeVal(e) {
let inputVal = e.detail.value,
inputindex = e.target.dataset.inputindex;
inputVal = inputVal.trim();
//对应输入项,存值
this.setData({
[`inputList[${inputindex}].value`]: inputVal
})
},
//点击提交循环字段并赋值
handleSubmit() {
let inputList = this.data.inputList,
dataList = {};
for (let item of inputList) {
//判断值是否为空且为必填项
if (!item.value&&item.required) {
wx.showToast({
icon: 'none',
title: item.tipMsg,
duration: 2000
})
return;
}
//对象新增属性并赋值
dataList[item.type] = item.value;
}
wx.request({
url: `${url}`,
header: {"Content-Type": "application/x-www-form-urlencoded"},
data:dataList,
method:'POST',
success: function (res) {
}
})
}
}
})
要点有:
输入时用input传的index拼接相对应的属性名进行赋值:
this.setData({
[`inputList[${inputindex}].value`]: inputVal
})
这里是在提交时,循环inputList的每个type作为属性名,value为属性值,进行对象属性新增和赋值:
dataList[item.type] = item.value;
点击提交,console.log(dataList);