**wxml关键配置:**关键属性:picker组件里的value=’{{categoryIndex}}’
<picker style='width:60%' bindchange='bindCategoryChange' name='categoryId' range-key='categoryName' value='{{categoryIndex}}' range='{{integralCategorys}}'> <view class='picker_value' style='width:100%'>{{integralCategorys[categoryIndex].categoryName}}</view> </picker> 123
其中integralCategorys是积分分类对象,里面包含id和categoryName;
js部分代码:
1.
data: { integralCategorys:null, integralItem:null, categoryIndex:null } 2. wx.request({ header: app.globalData.header, url: app.globalData.URL + '/integralItem/' + options.id, method: 'GET', dataType: 'json', responseType: 'text', success: function (res) { console.log(res.data.data); that.setData({ integralItem: res.data.data }); }, }) wx.request({ header:app.globalData.header, url: app.globalData.URL + '/integralCategory/getAllCategoryAndItems', method: 'GET', dataType: 'json', responseType: 'text', success: function (res) { console.log(res.data.data); that.setData({ integralCategorys: res.data.data }); }, }) for (var i = 0; i < that.data.integralCategorys.length; i++) { if (that.data.integralItem.categoryId == that.data.integralCategorys[i].id) { that.setData({ categoryIndex: [i] }) break; } }
12345678910111213141516171819202122232425262728293031323334353637383940414243各变量间关系:
integralItem是积分项对象,包含id,itemName,categoryId(积分分类ID)
integralCategorys所有的积分分类数组(所有的积分分类对象)(picker需要滚动选择的数据):积分分类 和积分项是1对多的关系
categoryIndex:积分项(integralItem)所在积分分类数组(integralCategory)的位置(数组下标)
实现过程
1、根据积分项ID获取积分项对象integralItem
2、查询所有积分分类对象数组:integralCategorys
3、遍历所有积分分类数组,找到该积分项的积分分类ID对应积分分类数组的位置,将积分分类的下标赋值。
4、将该数组下标赋值给picker组件的value属性
至此:picker组件就可以出现初始默认值了