前言
Vant之van-picker
级联选择
- 将自定义平铺结构转化为层级结构数据
- 动态
$set()
给每一条数据对象添加text
属性用于展示
数据处理
原始数据
[
{id: 'node1',pid: 'root',content: 'test'},
{id: 'node2',pid: 'root',content: 'test'},
{id: 'node3',pid: 'node1',content: 'test'},
{id: 'node4',pid: 'node2',content: 'test'},
{id: 'node5',pid: 'node3',content: 'test'},
{id: 'node6',pid: 'node1',content: 'test'}
]
转化后数据
[
{
id: 'node1',
pid: 'root',
content: 'test',
children: [
{
id: 'node3',
pid: 'node1',
ccontent: 'test',
children: [
{id: 'node5',pid: 'node3',content: 'test'}
]
},
{id: 'node6',pid: 'node1',content: 'test'}
]
},
{
id: 'node2',
pid: 'root',
content: 'test',
children: [
{id: 'node4',pid: 'node2',content: 'test'}
]
},
]
转化函数tile2nest
tile2nest(array, key, pKey, childrenKey) {
if (!array || array.constructor !== Array) {
return array;
}
let ary = [...array];
key = key || "id";
pKey = pKey || "parentId";
childrenKey = childrenKey || "children";
let ary2remove = [];
ary.map(item => {
this.$set(item,'text',item.name);
if (item[key] !== item[pKey]) {
let p = ary.filter(c => c[key] === item[pKey]);
if (p && p.length == 1) {
p[0].children = p[0].children || [];
p[0].children.push(item);
ary2remove.push(item[key]);
}
}
});
ary2remove.map(item => {
ary = ary.filter(c => c[key] !== item);
});
return ary;
}
使用组件
<van-field readonly clickable placeholder="一二级分类" :value="form.kind" @click="showPicker = true" />
<van-popup v-model="showPicker" position="bottom" :duration="0">
<van-picker show-toolbar title="分类选择" :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" @change="onChange" />
van-popup>
onConfirm(value) {
let str = "";
for(let i= 0;i<value.length;i++){
if(i>0){
str += "/" + value[i];
}
else{
str +=value[i];
}
}
this.form.kind = str;
this.showPicker = false
},
效果