Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap selectpicker VueJS directive

I'm trying to build a custom directive for Bootstrap that makes a <select> input into a "selectpicker" from Bootstrap selectpicker Also I would like this directive to use the default options functionality of VueJS for filling the options on a <select> So the html would be something like this:

<select v-selectpicker="myValue" options="myOptions"></select>

Now I can create the directive perfectly and use the bind method to call the selectpicker() method on the element. The problem seems to be the fact that the options are set after the call to selectpicker(). So somehow I need to either wait until the options are set, or I have to do another call to selectpicker(refresh) when the options are set.

Does anyone know if this is possible?

like image 719
RGweb Avatar asked Oct 20 '25 11:10

RGweb


2 Answers

The answer provided only works if you're serving your options from the server. Trying to init Bootstrap-select using Vue data as options always has it getting called before the options are rendered.

My solution was to use a component and pass in the options / select name and callback function as props that way I can be sure they are all loaded.

HTML

<select-picker :name.sync="itemsPerPage" :options.sync="itemsPerPageOptions" :function="changeItemsPerPage"></select-picker>    

JS - Selectpicker Component

Vue.component('select-picker', {
template:'<select v-model="name" class="themed-select" @change="function">' +
'<option v-bind:value="option.value" v-for="option in options">{{ option.label }}</option>' +
'</select>',
name: 'selectpicker',
props: ['options', 'name', 'function'],
updated: function() {
    console.log(this);
    $(this.$el).selectpicker({
        iconBase: 'fa',
        tickIcon: 'fa-check'
    });
}
});
like image 90
forkiven Avatar answered Oct 23 '25 05:10

forkiven


I've changed a little solution of mocheaz. It already sets initial value if select tag is placed dynamically:

require('bootstrap-select');

Vue.directive('selectpicker',
{
    twoWay: true,

    bind()
    {
        $(this.el).selectpicker();

        $(this.el).on('change', function(e) {
            this.set($(this.el).val());
        }.bind(this));
    },

    update(newValue)
    {
        $(this.el).val(newValue);
        $(this.el).selectpicker('val', newValue);
    },

    unbind()
    {
        $(this.el).selectpicker('destroy');
    }
});
like image 23
Łukasz Kuczmaja Avatar answered Oct 23 '25 04:10

Łukasz Kuczmaja