Bootstrap selectpicker VueJS指令

我正在尝试为Bootstrap构建一个自定义指令,从Bootstrap selectpicker中将 输入到“selectpicker”中。我也希望这个指令使用VueJS的默认optionsfunction来填充上的选项。 HTML将是这样的:

现在我可以完美地创建指令并使用bind方法在元素上调用selectpicker()方法。 问题似乎是在调用selectpicker()之后设置了选项。 所以我需要等到设置选项,或者在设置选项时我必须再次调用selectpicker(refresh)

有谁知道这是否可能?

提供的答案仅适用于您从服务器提供选项的情况。 尝试初始化Bootstrap-select使用Vue数据作为选项总是在呈现选项之前调用它。

我的解决方案是使用一个组件并将选项/选择名称和回调函数作为道具传递,我可以确定它们都已加载。

HTML

  

JS – Selectpicker组件

 Vue.component('select-picker', { template:'', name: 'selectpicker', props: ['options', 'name', 'function'], updated: function() { console.log(this); $(this.$el).selectpicker({ iconBase: 'fa', tickIcon: 'fa-check' }); } }); 

我改变了mocheaz的一点解决方案。 如果动态放置select标记,它已经设置了初始值:

 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'); } }); 

我这样做了,它对我有用。

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

这对于那些正在寻找能够使用bootstrap-select和vue.js(v2.5)的人来说非常有用

指示:

 Vue.directive('selectpicker', { inserted(el) { $(el).selectpicker( {/*options*/}, }); }, update(el, binding) { $(el).selectpicker('val', binding.value); }, componentUpdated(el) { $(el).selectpicker('refresh'); }, unbindel() { $(el).selectpicker('destroy'); } }); 

HTML: