项目遇到个需求了,就是使用picker去实现二级联动,由于本人比较菜,走了很多坑,最后还是请教同事老哥帮我实现的,但还是想将这个实现分享一下吧
本套代码语法是uniapp的原生实现,但不保证不出任何Bug!!!
仅供参考,仅供参考,仅供参考,可以先直接copy在空白页跑跑.

结构
<view>
<picker
mode="multiSelector"
@change="bindMultiPickerChange"
@columnchange="bindMultiPickerColumnChange"
:value="multiIndex"
:range="multiArray"
>
<view class="picker">
当前选择:{{multiArray[0][multiIndex[0]]}} > {{multiArray[1][multiIndex[1]]}}
</view>
</picker>
</view>
data的变量声明
data() {
return {
multiArray: [],
multiIndex: [0, 0],
//后台接口返回的数据结构
array: [{
name: '肉类',
id: 0,
children: [{
id: 1,
name: '猪肉',
},
{
id: 2,
name: '牛肉',
}
]
},
{
name: '菜类',
id: 1,
children: [{
id: 3,
name: '黄瓜',
},
{
id: 4,
name: '茄子',
}
]
},
],
oneId: 0,
twoId: 0,
};
},
JS
onLoad() {
this.initData(); //页面一加载调用赋值
},
methods: {
initData() { //首次加载渲染 第一列 和 第二列数据
const arrOne = this.array.map(item => {
return item.name; // 此方法将第一列 '名称'分到一个新数组中
});
const arrTwo = this.array[0].children.map(item => {
return item.name; // 此方法将第二列'名称'分到一个新数组中
});
this.multiArray[0] = arrOne;
this.multiArray[1] = arrTwo;
this.oneId = this.array[0].id;
this.twoId = this.array[0].children[0].id;
},
//滚动时候触发,
bindMultiPickerColumnChange(e) {
console.log(e.detail.column, "e.detail.column表示是第几列表示是第几列")
if (e.detail.column === 0) {
this.initSelect(e.detail.value);
this.multiIndex[0] = e.detail.value;
} else if (e.detail.column === 1) {
this.multiIndex[1] = e.detail.value;
this.twoId = this.array[this.multiIndex[0]].children[
this.multiIndex[1]
].id;
}
console.log(this.oneId, "打印第一列id");
console.log(this.twoId, "打印第二列id");
},
// 定义一个传入对应的'下标'为了拿到第一列id 和 第二列的name和id的方法
initSelect(index) {
this.oneId = this.array[index].id; //拿到第一列id
this.multiIndex[1] = 0; //将右边的数组的下标变回第一个显示
this.$set(this.multiArray, 1, []); //清空对应右边数组的数据
if (this.array[index].children.length == 0) {
console.log("如果右边长度等于0,那么清掉右边ID");
this.twoId = "";
} else {
const arrTwo = this.array[index].children.map(item => {
return item.name; // 将第一列的children的数组遍历 name返回到一个新数组接收
});
this.$set(this.multiArray, 1, arrTwo); //重新 赋值到新的数组里
this.twoId = this.array[index].children[0].id; //那么对应的第二列的第index个id也拿到了
}
},
// 点击确定时触发,这里点击处理自己的业务,应该就是拿到两个个id去请求
bindMultiPickerChange(e) {
console.log(this.oneId);
console.log(this.twoId);
// uni.request({
// url: ``,
// })
},
},
其实,应该是先从接口拿到数据,然后再对应的将接口数据赋值一个数组里,再去调用initData()再修改一下里面的字段就应该oK了,当然你有更好的方法是ok的,我现在也只是做个静态的,并没有接口就先这么写了,希望能帮到有这个需要的人叭(我也不能保证不出问题,只能做个参考吧),接口返回的字段不一定跟我相同,注意更改哦,然后就么了.