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?
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.
<select-picker :name.sync="itemsPerPage" :options.sync="itemsPerPageOptions" :function="changeItemsPerPage"></select-picker>
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'
});
}
});
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');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With