【sgLazyCascader】自定义组件:基于el-cascader的懒加载级联菜单,支持异步加载子级菜单

sgLazyCascader源码

<template>
    <div :class="$options.name">
        <el-cascader :props="props" v-model="model" :placeholder="placeholder || '请选择'" :options="options"></el-cascader>
    </div>
</template>
<script>
export default {
    name: 'sgLazyCascader',
    data() {
        return {
            model: null,
            mainKey: 'id',//默认主键
            defaultRootId: 'root',//默认根节点ID就是root
            form: {},
            props: {
                lazy: true,
                expandTrigger: 'hover',
                multiple: false,
                lazyLoad: (node, resolve) => {
                    this.loadNodeData(node.level === 0 ? { [this.mainKey]: this.defaultRootId } : node.data, d => resolve(d));
                }
            }
        }
    },
    props: [
        "value",
        "options",//回显的时候使用
        "data",
        "placeholder",
    ],
    watch: {
        value: { handler(d) { this.model = d; }, deep: true, immediate: true, },
        model(d) { this.$emit('input', d); },
        data: {
            handler(d) {
                d.nodeKey && (this.mainKey = d.nodeKey);//主键
                d.rootId && (this.defaultRootId = d.rootId);//根节点ID
                d.value && (this.props.value = d.value);//指定选项的值为选项对象的某个属性值
                d.label && (this.props.label = d.label);//指定选项标签为选项对象的某个属性值
                d.children && (this.props.children = d.children);//指定选项的子选项为选项对象的某个属性值	
                d.expandTrigger && (this.props.expandTrigger = d.expandTrigger);//次级菜单的展开方式click / hover
                d.hasOwnProperty('multiple') && (this.props.multiple = d.multiple);//是否多选	
                d.hasOwnProperty('lazy') && (this.props.lazy = d.lazy);//是否动态加载子节点,需与 lazyLoad 方法结合使用	
            }, deep: true, immediate: true,
        },
    },
    methods: {
        // 加载节点数据(通过接口向后台获取数据)
        loadNodeData(data, cb) {
            let resolve = d => { cb && cb(d) };
            this.$emit(`loadNode`, data, resolve);
        },
    },
};
</script> 

用例

<template>
    <div :class="$options.name">
        <sgLazyCascader v-model="value" :data="{
            nodeKey: `ID`,//主键
            value: `ID`,
            label: 'MC',
        }" :options="options" placeholder="请选择" @loadNode="loadNode" />
    </div>
</template>
    
<script>
import sgLazyCascader from "@/vue/components/admin/sgLazyCascader";
export default {
    components: {
        sgLazyCascader,
    },
    data() {
        return {
            value: [],
            options: [],
        }
    },
    methods: {
        // 加载节点数据
        loadNode(data, resolve) { this.$d.apiname({ data: { PID: data.ID }, doing: { s: d => resolve(d) } }); },
    }
};
</script>

猜你喜欢

转载自blog.csdn.net/qq_37860634/article/details/132757903