<!-- 
    Select2Component - Select2 komponenta sa 'statickim' podacima 
                       'data' treba da se prosledi kao niz objekata u formatu: [{id: 1, text: 'neki tekst' } ...]

    PRIMER UPOTREBE:
        <autoerp-select2 id="test" name="test" 
                         placeholder="Test" 
                         v-bind:data="view.select2data" 
                         v-model:value="view.select2selectedValue">
        </autoerp-select2>
-->

<template>
    <select v-bind:name="name" v-bind:id="id" class="form-control" v-bind:disabled="disabled">
    </select>
</template>

<script>

export default {
    props: { 
            id: { type: String, default:  'select2_' + Math.floor((Math.random() * 10000000) + 1) }, 
            name: { type: String }, 
            placeholder: { type: String },
            data: { type: Array },
            value: { type: [Number, String] }, 
            disabled: {type: Boolean, default: false},
            dropdownparentid: { type: String}
    },
    mounted() {
        var self = this;
        this.$select2 = $(this.$el).select2({
            placeholder: this.placeholder,
            data: this.data,
            dropdownParent: this.dropdownparentid ? $('#' + this.dropdownparentid) : $(document.body)
        })
        .on('change', function(e){
            self.$emit('input', this.value);
        })
        .val(this.value).trigger('change'); // setuj inicijalnu vrednost selektovane opcije
    },
    watch: {
        value: function (value) {
            // 'apdejtuj' vrednost selektovane opcije
            $(this.$select2)
                .val(value)
                .trigger('change')
            }        
    },
    destroyed() {
        $(this.$select2).off().select2('destroy')
    }
}
</script>