vant的Picker 选择器的数据回显
console.log("父级索引:", parentIndex);注意:这个需要计算出父级列和子级列对应的默认索引值,在Picker选择器改变时,可以用getColumnIndex来获取对应的索引值,但是考虑到Picker的对应的columnsregion可以会改变,这样在回显的时候可能会出现数据回显错误的情况,所以可以根据id来查找对应的索引值。
实现Picker 选择器的数据回显总共有三种方案:

(1)使用setColumnIndex的方法
<Popup
:lazy-render="false"
v-model="showtwo"
position="bottom"
:style="{ height: '60%' }"
>
<Picker
ref="pickerDialog"
show-toolbar
title="筛选"
:columns="columnsregion"
@confirm="onConfirm"
@cancel="onCancel"
/>
</Popup>
0 表示选择器的第一列,1表示选择器的第二列
parentIndex 用于设置选择器的第一列(父级列)的选项索引值
childIndex 用于设置选择器的第二列(子级列)的选项索引值
this.$refs.pickerDialog.setColumnIndex(0, parentIndex);
this.$refs.pickerDialog.setColumnIndex(1, childIndex);
注意:这个需要计算出父级列和子级列对应的默认索引值,在Picker选择器改变时,可以用getColumnIndex来获取对应的索引值,但是考虑到Picker的对应的columnsregion可以会改变,这样在回显的时候可能会出现数据回显错误的情况,所以可以根据id来查找对应的索引值
获取索引值的方法:
function findParentChildIndex(data, id) {
for (let i = 0; i < data.length; i++) {
const parent = data[i];
const childIndex = parent.children.findIndex(child => child.Id === id);
if (childIndex !== -1) {
return { parentIndex: i, childIndex: childIndex, childText: parent.children[childIndex].text };
}
}
return { parentIndex: -1, childIndex: -1, childText: "" }; // 如果未找到则返回空字符串
}
const idToFind = "5"; const { parentIndex, childIndex, childText } = findParentChildIndex(columnsregion, idToFind); console.log("父级索引:", parentIndex); console.log("子级索引:", childIndex); console.log("子级文本:", childText);
(2)使用setIndexes的方法
this.$refs.pickerDialog.setIndexes([parentIndex, childIndex]);
parentIndex 表示第一列的选项索引 childIndex表示第二列的选项索引
(3)使用setColumnValue的方法
this.$refs.pickerDialog.setColumnValue(0, "区域1");
this.$refs.pickerDialog.setColumnValue(1, "区域3");
区域1 表示第一类的value 区域3 表示第二列的value,但是使用这个可能会出现几个对象的text一样,这样返回的数据就不对了,所以不建议使用
注意1:在vant-popup里面把area-picker标签包裹起来,默认是懒加载的,这时候使用this.$refs.pickerDialog是undefined,所以必须在vant-popup标签把懒加载关闭
解决方案::lazy-render="false"

注意2:这种情况下, 在实际的开发过程中this.$refs.pickerDialog能取到,但是使用this.$refs.pickerDialog.setIndexes([parentIndex, childIndex]);没效果,需要使用 this.$nextTick 方法。
this.$nextTick 是 Vue.js 提供的一个方法,用于在 DOM 更新之后执行回调函数。它的作用是确保在下次 DOM 更新循环结束之后再执行回调函数,以便获取到更新后的 DOM 元素状态
this.$nextTick(() => {
this.$refs.pickerDialog.setIndexes([parentIndex, childIndex]);
});
这时候就能完全实现这个功能了
在Popup中使用:lazy-render="false"
<Popup
:lazy-render="false"
v-model="showtwo"
position="bottom"
:style="{ height: '60%' }"
>
<Picker
ref="pickerDialog"
show-toolbar
title="筛选"
:columns="columnsregion"
@confirm="onConfirm"
@cancel="onCancel"
/>
</Popup>
更多推荐


所有评论(0)