elementui文档提到的lazyLoad懒加载方法,回显做不出来,最后使用了简单粗暴的方法,欢迎大神指点
<el-cascader v-model="value" :props="props" :options="options" @change="handleChange" @expand-change="fn"></el-cascader>
<el-button @click="huixian">回显</el-button>
@change为选中节点事件,@expand-change为点击节点事件
<script>
// getCityList获取省份数据 getCityById 通过areaCode获取子级数据
import { getCityList, getCityById } from '@/api/indexpage.js'
export default {
name: 'test',
data() {
return {
value: '',
options: [],
props: {
checkStrictly: true, //单选
value: 'areaCode',
label: 'name',
},
}
},
mounted() {},
created() {
this.getSheng()
},
methods: {
// 省级数据
getSheng() {
getCityList().then((res) => {
this.options = res.data
})
},
handleChange(e) {
console.log(e)
},
fn(e) {
getCityById(e[e.length - 1]).then((res) => {
const obj = this.findNodeById(this.options, e[e.length - 1])
obj.children = res.data
})
},
//回显数据,根据后端返回areaCode列表循环遍历获取到所有数据,赋值给options
async huixian() {
const data = [120000000000, 120100000000, 120102000000, 120102003000, 120102003005]
this.value = data
for (let i = 0; i < data.length; i++) {
// 等每个循环体都有结果再进行下一次循环,不然接口调用顺序打乱
await getCityById(data[i]).then((res) => {
console.log(res)
const obj = this.findNodeById(this.options, data[i])
if (res.data.length) {
obj.children = res.data
}
})
}
},
// 递归查找选中节点并将子节点添加至children
findNodeById(data, areaCode) {
for (let i = 0; i < data.length; i++) {
const node = data[i]
if (node.areaCode === areaCode) {
return node
}
if (node.children && node.children.length > 0) {
const result = this.findNodeById(node.children, areaCode)
if (result !== null) {
return result
}
}
}
return null
},
},
}
</script>