index.vue 1.92 KB
Newer Older
1
<template>
2 3
    <el-select v-model="valueSync" :multiple="multiple" :disabled="disabled" :filterable="filterable">
        <el-option v-for="item in optionsFormated" :key="item.key" :label="item.label" :value="item.value" />
4 5 6 7 8 9 10 11 12 13 14 15 16
    </el-select>
</template>
<script>
export default {
    data(){
        return {
            valueSync: null
        }
    },
    props:{
        options: Array,
        value: [String, Number, Boolean, Object],
        labelField: {
17
            type: [String, Function],
18 19 20 21 22 23
            default: 'label'
        },
        valueField: {
            type: String,
            default: 'value'
        },
24 25 26 27 28
        keyField:{
            type: String,
            default: 'value'
        },
        filterable: Boolean,
29 30 31
        multiple: Boolean,
        clearable: Boolean,
        defaultable: Boolean, // 没有值的时候是否选择第一项
32
        disabled: Boolean
33 34 35 36
    },
    computed:{
        optionsFormated(){
            let arr = []
37
            this.options.forEach((item, index) => {
38
                arr.push({
39
                    label: typeof this.labelField == 'string' ? item[this.labelField] : (this.labelField)(item, index),
40 41
                    value: item[this.valueField],
                    key: item[this.keyField]
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
                })
            })
            return arr
        }
    },
    watch:{
        valueSync(val){
            this.$emit('input', val)
        },
        value(value){
            this.valueSync = value
        },
        optionsFormated(){
            this.setDefault()
        }
    },
    created(){
        this.valueSync = this.value
        this.setDefault()
    },
    methods:{
        setDefault(){
            if(!this.defaultable){
                return false
            }
            if(this.optionsFormated.length && (this.valueSync == null || this.valueSync == '')){
                this.valueSync = this.optionsFormated[0].value
            }
        }
    }
}
</script>