kakallatt's avatar

Select2 and Vue Directive

I am integrating a jQuery select2 plugin by wrapping it inside a custom directive.

    export default {

        data() {
            return {
                selected: null,
                options: []
            }
        },

        ready() {
        this.fetchUsers()
    }

        methods: {
            fetchUsers: function () {
                this.$http({
                    url: '/api/users/get-all',
                    method: 'GET'
                }).then(function (response) {
                    this.$set('options', response.data)
                }, function (response) {
                    // error callback
                });
            }
        },

        directives: {
            select: {
                twoWay: true,
                priority: 1000,

                params: ['options'],

                bind: function () {
                    var self = this;

                    $(this.el)
                            .select2({
                                theme: "bootstrap",
                                closeOnSelect: true,
                                minimumInputLength: 3,
                                data: this.params.options
                            })
                            .on('change', function () {
                                self.set(this.value)
                            })
                },
                update: function (value) {
                    $(this.el).val(value).trigger('change')
                },
                unbind: function () {
                    $(this.el).off().select2('destroy')
                }
            }
        }

    }
<select v-select="selected" :options="options"></select>

I try to get all users and set to options in fetchUsers function, but seem fetchUsers function was executed after select2 directive so the options variable always be empty.

So how can I get all users through ajax (vue-resource) and after that populate to select2?

0 likes
7 replies
dcranmer's avatar

I'd say that choice of whether to use Select2's built-in AJAX support or Vue (via the vue-resource plugin) depends on the needs of your project. Both will work. I happen to be using the Vue + vue-resource along with Select2, and it is quite straightforward to fetch data and populate the dropdown.

maasarwar's avatar

It's working for me .

//view blade:


{{ Form::select('supplier_id', $suppliers , null, ['id' => 'supplier_id', 'class'=>'form-control','v-model'=>'supplier_id','v-select'=>'supplier_id']) }}


script on bottom

$('#supplier_id').select2({ placeholder: "Select a Supplier", allowClear: true });

//controller


    $suppliers= \App\Supplier::lists('company','id')->toArray();
        return view('purchases.create',compact('suppliers'));

//vue js (I global directive, you can use for any)

Vue.directive('select', {
    twoWay: true,
    bind: function () {
        $(this.el).select2()
        .on("select2:select", function(e) {
            this.set($(this.el).val());
        }.bind(this));
        },
    update: function(nv, ov) {
        $(this.el).trigger("change");
    }
});

1 like
anzglobalsoft's avatar

** I hope this might help you**

<template>
    <select :name="name" :id="identifier" class="form-control">
        <option v-for="selecteditem in selecteditems" :key="selecteditem.id" :value="selecteditem.id">
            {{selecteditem.name}}
        </option>
    </select>
</template>

<script>

export default {
    props: ['selecteditems', 'identifier', 'name', 'url'],
    data() {
        return {

        }
    },
    created(){
        
    },
    mounted(){
        $('#' + this.identifier).select2({
            placeholder: 'Select Client',
            ajax: {
                url: this.url,
                data: function (params) {
                var query = {
                    search: params.term
                }

                // Query parameters will be ?search=[term]&type=public
                return query;
                },
                processResults: function (data) {
                    return {
                        results: data
                    };
                },
                cache: false
            }
        });
    }
}
</script>

** app.js **

Vue.component(
    'select2',
    require('./components/reusable/SelectComponent.vue')
);

** api controller code **

public function dropdown(Request $request)
{
    $term = trim($request->query('search'));
    return Product::search($term)->paginate(20);
}

** View **

<select2 
url="api/category/dropdown" 
name="category_id" 
:selecteditems="[{id: 1, name: 'abc'}]" 
identifier="product">
</select2>

Please or to participate in this conversation.