需求描述:
通过请求后端接口,获取到数据源(json格式,数组),使用小程序wx:for循环遍历,对接口返回的数组中的一个字段存为picker组件选择器,并允许用户进行选择修改该值。
问题描述:
在使用wx:for循环时,picker选择器修改值操作直接使用this.setData({index:e.detail.value})的方式进行修改保存,使用这种方式就会出现picker选择器渲染完毕后,对其中的某个选择器的值进行修改,相对应的,所有使用wx:for循环遍历出的picker选择器的值均会修改(原因:picker选择器共用value所影响)。
代码呈上:
<!-- wxml -->
<view class="card" wx:for='{{inventory}}' wx:key='{{item.ID}}'>
<view class="cardtop">
<view class="cardleft">
<text>修改状态:</text>
</view>
<view class="cardright">
<picker bindchange="bindPickerChange" value="{{index}}" range="{{array}}" range-key='text'>
<input placeholder='请选择' disabled" value='{{array[index].text}}'></input>
</picker>
</view>
</view>
</view>
// js
data: {
array: [
{index:'1',text:"发回公司"},
{index:'2',text:"原地封存"},
{index:'3',text:"待调剂"}
],
index:0
},
bindPickerChange: function (e) {
this.setData({
index: e.detail.value
});
},
解决方案:
思路:对后台返回的数据进行处理,在后台返回的数组中每一项添加当前picker选择器修改后的值,picker选择器选项字段,在循环所有picker选择器时,通过给picker选择器绑定不同的索引,通过索引去监听哪个picker选择器的值进行改变,进行改变后的picker选择器记录对应改变的值后,重新赋值即解决动态生成picker选择器后修改值相互影响问题。
代码呈上:
<!-- wxml -->
<!-- 使用 wx:for-index 指定数组当前下标的变量名为idx -->
<view class="card" wx:for='{{inventory}}' wx:key='{{item.ID}}' wx:for-index="idx">
<view class="cardtop">
<view class="cardleft">
<text>修改状态:</text>
</view>
<view class="cardright">
<!-- picker自定义一个属性对应当前下标 data-current="{{idx}},绑定事件bindPickerChange触发时判断出是哪个数组对象触发的,就改变该数组对象中的index值" -->
<picker bindchange="bindPickerChange" value="{{item.index}}" range="{{item.option}}" data-current="{{idx}}">
<input placeholder='请选择' disabled value='{{item.option[item.index]}}'></input>
</picker>
</view>
</view>
</view>
// 因不能用this.setData直接设置每个对象的索引值index,故用自定义属性current来标记每个数组对象的下标
bindPickerChange: function(e) {
// 储存触发事件的数组对象的下标
const curindex = e.target.dataset.current;
// 根据下标改变该数组对象中的index值
this.data.inventory[curindex].index = e.detail.value;
// 把改变某个数组对象index值之后的全新inventory重新赋值给inventory
this.setData({
inventory: this.data.inventory
});
},
// 后台返回数据处理
wx.request({
url: 'xxxxx',
method: 'POST',
header: {
'cookie': wx.getStorageSync("sessionid"), //读取cookie
'content-type': 'application/x-www-form-urlencoded'
},
success: function(res) {
if (res != null && res != '') {
for(var i = 0 ;i < res.data.length;i++){
let key1 = 'index';
let jValue1 = '';
res.data[i][key1] = jValue1;
let key2 = 'option';
let jValue2 = ['发回公司','原地封存','待调剂'];
res.data[i][key2] = jValue2;
}
_this.setData({
inventory: res.data
})
}
}
})