<template>
    <el-select v-model="valueSync" :multiple="multiple">
        <el-option v-for="item in optionsFormated" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
</template>
<script>
export default {
    data(){
        return {
            valueSync: null
        }
    },
    props:{
        options: Array,
        value: [String, Number, Boolean, Object],
        labelField: {
            type: String,
            default: 'label'
        },
        valueField: {
            type: String,
            default: 'value'
        },
        multiple: Boolean,
        clearable: Boolean,
        defaultable: Boolean, // 没有值的时候是否选择第一项
    },
    computed:{
        optionsFormated(){
            let arr = []
            this.options.forEach(item => {
                arr.push({
                    label: item[this.labelField],
                    value: item[this.valueField]
                })
            })
            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>