一、初始代码
<view class="uni_cell"> <view class="uni_cell_left">年龄段选择</view> <view class="uni_cell_db"> <picker @change="bindPickerChange" :value="index_1" :range="age_array" range-key="age"> <view class="uni-input">{{age_array[index_1].age}}</view> </picker> </view> </view> <view class="uni_cell"> <view class="uni_cell_left">性别选择</view> <view class="uni_cell_db"> <picker @change="bindPickerChange" :value="index_2" :range="sex_array" range-key="sex" > <view class="uni-input">{{sex_array[index_2].sex}}</view> </picker> </view> </view>
export default{ data(){ return{ title:'picker', age_array:[{age:'17岁以下'},{age:'18-35岁'},{age:'35-65岁'},{age:'65岁以上'}], sex_array:[{sex:'男'},{sex:'女'}], career_array:[{career:'学生'},{career:'个体户'},{career:'财务人员'},{career:'一般工人'},{career:'全职宝妈'},{career:'离休人员'},{career:'其他'}], index_1:0, index_2:0, } }, methods:{ bindPickerChange: function(e) { console.log('picker发送选择改变,携带值为:' + e.detail.value) this.index_1 = e.detail.value this.index_2 = e.detail.value } } }
二、出现情况
选择一个picker之后所有选择器的数据都会随之更改,三个picker依据同个value显示值
三、解决办法
e.currentTarget.dataset: 获取标签中定义的值,定义方法 data-*=某个值
<view class="uni_cell">
<view class="uni_cell_left">年龄段选择</view>
<view class="uni_cell_db">
<picker @change="bindPickerChange" :value="index_1" :range="age_array" range-key="age" data-index="1">
<view class="uni-input">{{age_array[index_1].age}}</view>
</picker>
</view>
</view>
<view class="uni_cell">
<view class="uni_cell_left">性别选择</view>
<view class="uni_cell_db">
<picker @change="bindPickerChange" :value="index_2" :range="sex_array" range-key="sex" data-index="2">
<view class="uni-input">{{sex_array[index_2].sex}}</view>
</picker>
</view>
</view>
<view class="uni_cell">
<view class="uni_cell_left">职业选择</view>
<view class="uni_cell_db">
<picker @change="bindPickerChange" :value="index_3" :range="career_array" range-key="career" data-index="3">
<view class="uni-input">{{career_array[index_3].career}}</view>
</picker>
</view>
</view>
bindPickerChange:function(e){
const pickerIndex = e.currentTarget.dataset.index;
console.log('picker发送选择改变,携带值为:' + e.detail.value)
switch (pickerIndex) {
case '1':
this.index_1 = e.detail.value;
break;
case '2':
this.index_2 = e.detail.value;
break;
case '3':
this.index_3 = e.detail.value;
break;
default:
break;
}
}