项目中有用到省市区选择,我们是三个接口获取数据的,在此记录一下级联和树形的区别:
级联HTML:
<el-cascader :props="region"></el-cascader>
级联JS:
1 region: { 2 lazy: true, 3 lazyLoad(node, resolve){ 4 if(node.level === 0){ 5 getProvince().then(val =>{ 6 if (val.code == 200) { 7 const nodes = val.data.map(res =>({ 8 label: res.name, 9 level: node.level, 10 value: res 11 })) 12 resolve(nodes) 13 } 14 }).catch(val=>{ 15 console.log(val) 16 }) 17 }else if(node.level === 1){ 18 getCity(node.data.value.provinceId).then(value =>{ 19 const nodes = value.data.map(res => ({ 20 label: res.name, 21 level: node.level, 22 value: res 23 })) 24 resolve(nodes) 25 }) 26 }else if(node.level === 2){ 27 getCountry(node.data.value.cityId).then(value => { 28 const nodes = value.data.map(res => ({ 29 label: res.name, 30 leaf: node.level, 31 value: res 32 })) 33 resolve(nodes) 34 }) 35 }else if(node.leve === 3){ 36 resolve([]) 37 } 38 } 39 },
树形HTML:
<el-tree ref="tree" :props="props" :load="loadNode" lazy node-key="id" highlight-current :default-expanded-keys="[1]" @node-click="handleNodeClick" />
树形JS:
// 树形
data(){
return {
props: {
id: 1,
label: 'name',
childern: 'zones'
}
}
},
methods:{
loadNode(node, resolve) {
if (node.level === 0) {
//默认打开第一级(id: 1)
return resolve([{ name: '单位列表', level: node.level, id: 1 }])
} else if (node.level === 1) {
getProvince()
.then(val => {
// console.log(val);
if (val.code === 200) {
const nodes = val.data.map(res => ({
name: res.name,
level: node.level,
value: res
}))
resolve(nodes)
}
})
.catch(val => {
this.$message.error(val)
})
} else if (node.level === 2) {
getCity(node.data.value.provinceId)
.then(val => {
if (val.code === 200) {
const nodes = val.data.map(res => ({
name: res.name,
level: node.level,
value: res
}))
resolve(nodes)
}
})
.catch(val => {
this.$message.error(val)
})
} else if (node.level === 3) {
getCountry(node.data.value.cityId)
.then(val => {
if (val.code === 200) {
const nodes = val.data.map(res => ({
name: res.name,
level: node.level,
value: res
}))
resolve(nodes)
}
})
.catch(val => {
this.$message.error(val)
})
} else if (node.level === 4) {
resolve([])
}
},
handleNodeClick(data) {
// console.log(data);
if(data.level === 3){
//方法
}
}
}