动态懒加载级联选择器el-cascader输入及回显

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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值